问:
Update trigger assistance
Evening, needing assistance regarding triggers.

Within my development environment I have two tables, one containing employee data (which contains various data errors that will be amended via ALTER TABLE) and the log table.

How do i go about designing a trigger that will update multiple rows contained within the log table such as 'issue_status','status_update_date' when ALTER TABLE sql is used to amend the data contained in the first data table?

-- employee table

```<code> CREATE TABLE emp(
emp_id  INTEGER NOT NULL,
emp_name    VARCHAR(30),
emp_postcode    VARCHAR(20),
emp_registered  DATE,
CONSTRAINT  pk_emp PRIMARY KEY (emp_id));
</code>```

-- SQL for the log table

```<code>    CREATE TABLE data_log
    (issue_id NUMBER(2) NOT NULL,
    table_name VARCHAR2(20),
    row_name VARCHAR2(20),
    data_error_code NUMBER(2),
    issue_desc VARCHAR2(50),
    issue_date DATE,
    issue_status VARCHAR2(20),
    status_update_date DATE);
</code>```

-- example log insert

```<code>    INSERT INTO data_log( SELECT DI_SEQ.nextval, 'emp', emp.emp_id, '1', 'emp_name case size not UPPER', SYSDATE, 'un-fixed', '' FROM emp WHERE emp_name != UPPER(emp_name));
</code>```

This is the example of the issue inserted into the log table. All i want to do is if I update the emp table to set 'emp_name' to Upper the trigger will register this update and change the rows 'issue_status' and 'status_update_date' to 'fixed' and the 'sysdate' of when the change was made

I've done some browsing however i'm still struggling to understand, any literature recommendations would be appreciated also.

Thanks in advance for the assistance.

答:
Note that we don't use ALTER TABLE to update the rows of a table as you have mentioned.We use Update statement. Your trigger should be a BEFORE UPDATE TRIGGER like this.

```<code>CREATE OR REPLACE TRIGGER trig_emp_upd BEFORE
    UPDATE ON emp
    FOR EACH ROW
    WHEN ( new.emp_name = upper(old.emp_name) )
BEGIN
    UPDATE data_log
        SET
            issue_status = 'fixed',
            status_update_date = SYSDATE
    WHERE
        row_name =:new.emp_id;

END;
/
</code>```

Title: Update trigger assistance

Body:
Evening, needing assistance regarding triggers.

Within my development environment I have two tables, one containing employee data (which contains various data errors that will be amended via ALTER TABLE) and the log table.

How do i go about designing a trigger that will update multiple rows contained within the log table such as 'issue_status','status_update_date' when ALTER TABLE sql is used to amend the data contained in the first data table?

-- employee table

 CREATE TABLE emp(
emp_id  INTEGER NOT NULL,
emp_name    VARCHAR(30),
emp_postcode    VARCHAR(20),
emp_registered  DATE,
CONSTRAINT  pk_emp PRIMARY KEY (emp_id));

-- SQL for the log table

    CREATE TABLE data_log
    (issue_id NUMBER(2) NOT NULL,
    table_name VARCHAR2(20),
    row_name VARCHAR2(20),
    data_error_code NUMBER(2),
    issue_desc VARCHAR2(50),
    issue_date DATE,
    issue_status VARCHAR2(20),
    status_update_date DATE);

-- example log insert

    INSERT INTO data_log( SELECT DI_SEQ.nextval, 'emp', emp.emp_id, '1', 'emp_name case size not UPPER', SYSDATE, 'un-fixed', '' FROM emp WHERE emp_name != UPPER(emp_name));

This is the example of the issue inserted into the log table. All i want to do is if I update the emp table to set 'emp_name' to Upper the trigger will register this update and change the rows 'issue_status' and 'status_update_date' to 'fixed' and the 'sysdate' of when the change was made

I've done some browsing however i'm still struggling to understand, any literature recommendations would be appreciated also.

Thanks in advance for the assistance.

Body:
Note that we don't use ALTER TABLE to update the rows of a table as you have mentioned.We use Update statement. Your trigger should be a BEFORE UPDATE TRIGGER like this.

CREATE OR REPLACE TRIGGER trig_emp_upd BEFORE
    UPDATE ON emp
    FOR EACH ROW
    WHEN ( new.emp_name = upper(old.emp_name) )
BEGIN
    UPDATE data_log
        SET
            issue_status = 'fixed',
            status_update_date = SYSDATE
    WHERE
        row_name =:new.emp_id;

END;
/


来源: stackexchange

问:
Play default soft keyboard sound when buttons are pressed in android
I have developed an app which uses my own custom keyboard (well, a view that looks like a keyboard and behaves like a keyboard anyway). One thing I've yet to figure it out is how to make it play the default soft keyboard 'click' sound when the buttons are pressed.
Is there any easy way to do this?

I would like to use the keyboard click sound that comes with the phone rather than providing my own. As different phones might have different keyboard click sounds, I would like to keep my application consistent. Ultimately, I want to reflect the same settings the user has chosen in their global keyboard settings (play/not play sounds, vibrate/not vibrate, etc).

答:
```<code>if (isSetVibration) {
        if (Build.VERSION.SDK_INT >= 26) {
            ((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(VibrationEffect.createOneShot(50, VibrationEffect.DEFAULT_AMPLITUDE));
        } else {
            ((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(50);
        }
    } else {
        if (Build.VERSION.SDK_INT >= 26) {
            ((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(VibrationEffect.createOneShot(0, VibrationEffect.DEFAULT_AMPLITUDE));
        } else {
            ((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(0);
        }
    }
</code>```

ContentLicense: CC BY-SA 3.0


问:
Static URL for a JDK?
I'm building an NSIS installer to install my application under Windows, and it will check if a user has a JDK (>= 1.5) and download and launch the installer for it if they do not.

While I have seen URLs for use in downloading JREs, I have not seen ones for the JDK.  If I copy and paste the URL I finally get after clicking through several pages to get the Windows (32-bit) (with nothing else bundled) JDK, the URL changes every time.

My users are not technically savvy and may not be able to download the JDK themselves from the starting page, so making them do so is suboptimal.

Is there a URL I can consistently use to download the JDK?

答:
Google reports 0 results on a query:

"jdk-6u23-windows-i586.exe" site:sun.com

So, I suppose there are no such web directory at the official site.

Solution 1: You can use this stable link to the particular JDK version and update it in future versions of your installer.

Solution 2: You need a JDK, but it is not fully redistributable. If you need only a compiler from JDK then you may try to join a redistributable JRE with a redistributable javac.exe and bundle it with your application (see JRE Version 5.0 README):

The J2SE(TM) Runtime Environment (JRE) is intended for software developers
  and vendors to redistribute with their applications.

...

Redistributable JDK(TM) Files

The limited set of files from the JDK listed below may be included in
  vendor redistributions of the J2SE Runtime Environment.  All paths
  are relative to the top-level directory of the JDK.

...

The javac bytecode compiler, consisting of the following files:

   bin/javac.exe [Microsoft Windows]

     lib/tools.jar [All platforms]

Solution 3: Download all JRE (pure or joined with the compiler) versions a priori to your application's web directory. You should check twice a license agreement before.

ContentLicense: CC BY-SA 2.5

Title: Static URL for a JDK?


问:
Unit testing JavaScript function with ForEach with Tape and Sinon
I am struggling to unit test the following function. In particular I cannot get it to cover the highlighted code:

```<code>function authCert(trustedCAFile){
    let ca = [];
    let cert = [];
    let trustedCA = String(fs.readFileSync(trustedCAFile));
    let trustedCALines = trustedCA.split("\n");

    trustedCALines.forEach(function(entry){

    cert.push(entry);
    if(entry.match(/-END CERTIFICATE-/)){
        **ca.push(cert.join("\n"));
        cert = [];**
    }
});

return ca;
}
</code>```

This is my current test:

```<code>let test = require('tape');
let rewire = require('rewire');
let sinon = require('sinon');
let fs = require('fs');
let proxyquire = require('proxyquire');

test('should cycle through trusted ', function(t) {
  let authCert = rewire('../authCert');
  let getAuthCerts = certUtils.getAuthCert;

  let certStub = 'test';

  let fsStub = {
      readFileSync: () => {}
  };

  let ca = [];
  ca.push('1');

  certUtils.__set__('fs', fsStub);

  let result = getAuthorisedCerts(certStub);

  t.deepEquals(result, []);
  t.end();

});
</code>```

I have looked at the documentation but as a noob I am unsure how to go about getting coverage and testing the highlighted code.

If anyone could help me or point me in the right direction I'd be very grateful.

Thanks

答:
You don't need proxyquire (not actually being used) or rewire to do the testing you want to do.

We can just use sinon to stub the fs object for the tests.

In terms of getting the coverage you wanted, all you needed to do was to make the readFileSync stub actually return something containing at least one '-END CERTIFICATE-'.

```<code>const test = require('tape');
const sinon = require('sinon');
const fs = require('fs');

const certUtils = require('../authCert');
const caFilePath = 'test';

test('should return each certificate', function(t) {
  const fileContents = 'cert1\n-END CERTIFICATE-\ncert2\n-END CERTIFICATE-';
  const fsStub = sinon.stub(fs, 'readFileSync').returns(fileContents);
  const result = certUtils.getAuthCert(caFilePath);

  fsStub.restore();

  t.deepEquals(result, ['cert1\n-END CERTIFICATE-', 'cert2\n-END CERTIFICATE-']);
  t.end();
});
</code>```

I've taken some liberties in terms of let/const and structuring the file, the key changes you need are making the stub return the string I've called fileContents.

Body:
I am struggling to unit test the following function. In particular I cannot get it to cover the highlighted code:

function authCert(trustedCAFile){
    let ca = [];
    let cert = [];
    let trustedCA = String(fs.readFileSync(trustedCAFile));
    let trustedCALines = trustedCA.split("\n");

    trustedCALines.forEach(function(entry){

    cert.push(entry);
    if(entry.match(/-END CERTIFICATE-/)){
        **ca.push(cert.join("\n"));
        cert = [];**
    }
});

return ca;
}

This is my current test:

let test = require('tape');
let rewire = require('rewire');
let sinon = require('sinon');
let fs = require('fs');
let proxyquire = require('proxyquire');

test('should cycle through trusted ', function(t) {
  let authCert = rewire('../authCert');
  let getAuthCerts = certUtils.getAuthCert;

  let certStub = 'test';

  let fsStub = {
      readFileSync: () => {}
  };

  let ca = [];
  ca.push('1');

  certUtils.__set__('fs', fsStub);

  let result = getAuthorisedCerts(certStub);

  t.deepEquals(result, []);
  t.end();

});

I have looked at the documentation but as a noob I am unsure how to go about getting coverage and testing the highlighted code.

If anyone could help me or point me in the right direction I'd be very grateful.

Thanks

Body:
You don't need proxyquire (not actually being used) or rewire to do the testing you want to do.

We can just use sinon to stub the fs object for the tests.

In terms of getting the coverage you wanted, all you needed to do was to make the readFileSync stub actually return something containing at least one '-END CERTIFICATE-'.

const test = require('tape');
const sinon = require('sinon');
const fs = require('fs');

const certUtils = require('../authCert');
const caFilePath = 'test';

test('should return each certificate', function(t) {
  const fileContents = 'cert1\n-END CERTIFICATE-\ncert2\n-END CERTIFICATE-';
  const fsStub = sinon.stub(fs, 'readFileSync').returns(fileContents);
  const result = certUtils.getAuthCert(caFilePath);

  fsStub.restore();

  t.deepEquals(result, ['cert1\n-END CERTIFICATE-', 'cert2\n-END CERTIFICATE-']);
  t.end();
});

I've taken some liberties in terms of let/const and structuring the file, the key changes you need are making the stub return the string I've called fileContents.


问:
Rails joins doesn't return values from joined table
It must be something pretty simple i'm doing wrong. i'm trying to join 3 tables together, where group contains a location_id which references a row in location and a info_id which does the same for info.

Here's my code:

```<code>@groups = Group.joins(
    'INNER JOIN location on location.id = "group".id',
    'INNER JOIN info on info.id = "group".id'
)
</code>```

This seems to work without errors, but all i'm getting back is the column from my group table. What am I doing wrong here?

P.S. my associations are location and info belong_to group. and group has_one of location and info

答:
In Rails / AR we have includes and joins.

You are using joins. As the SQL shows, it only selects Group. You use joins when you need Group results but also want to query through Location and Info.

If you would use all information, which I suspect is your case, like to display details in a table, you should also use includes.

```<code># @groups = Groups.includes(:locations, :info) results an left outer join
@groups = Groups.joins(:locations, :info).includes(:locations, :info) # results inner join
</code>```

Now when you do some thing like this it will not make additional db calls. But if you use joins it use multiple queries (N+1).

```<code>- @groups.each do |group|
  tr
    td = group.id
    td = group.location.lat
    td = group.info.description
</code>```

Use the bullet gem to find if you have such N+1 queries to optimize your project.

If you Google Rails includes vs joins you will find more information on the topic.

Body:
It must be something pretty simple i'm doing wrong. i'm trying to join 3 tables together, where group contains a location_id which references a row in location and a info_id which does the same for info.

Here's my code:

@groups = Group.joins(
    'INNER JOIN location on location.id = "group".id',
    'INNER JOIN info on info.id = "group".id'
)

This seems to work without errors, but all i'm getting back is the column from my group table. What am I doing wrong here?

P.S. my associations are location and info belong_to group. and group has_one of location and info

Body:
In Rails / AR we have includes and joins.

You are using joins. As the SQL shows, it only selects Group. You use joins when you need Group results but also want to query through Location and Info.

If you would use all information, which I suspect is your case, like to display details in a table, you should also use includes.

# @groups = Groups.includes(:locations, :info) results an left outer join
@groups = Groups.joins(:locations, :info).includes(:locations, :info) # results inner join

Now when you do some thing like this it will not make additional db calls. But if you use joins it use multiple queries (N+1).

- @groups.each do |group|
  tr
    td = group.id
    td = group.location.lat
    td = group.info.description

Use the bullet gem to find if you have such N+1 queries to optimize your project.

If you Google Rails includes vs joins you will find more information on the topic.


问:
Error: A(:) = B, the number of elements in A and B must be the same
As I understand the ber matrix is not matching with err. Need help to overcome the error in the following code:

```<code>for snr= 1:50
err=0;
ber = err;
No= 1/10^(snr/10);
    for i= 1: 10^6;
        x= sign (randn(2,1));
        h= randn (1,2) * sqrt(1/2) + sqrt (1/2)* 1j* randn(1,2);
        w= sqrt(No/2)* randn (1,2) + sqrt(No/2)*1j* randn(1,2);
        alamh=[ h(1) h(2); conj(h(2)) -conj(h(1))];
        y= alamh * x + transpose(w);
        h_pseudoinverse= inv(ctranspose(alamh)* alamh)\ ctranspose(alamh);
        r= x + h_pseudoinverse * transpose (w);
        est_x= sign(real(r));
        err= (est_x~=x)+err;
    end
ber(snr)= err/10^6;
end

semilogy (1:50, ber,'-O')
</code>```

Error:

Error: A(:) = B, the number of elements in A and B must be the same

答:
After the inner loop runs, err is a 2x1 matrix. If you want to store each iteration of err in ber then you can, for example:

(1) add the line ber = NaN(2, 50); before your code,

(2) delete the line ber = err;, and

(3) change the line ber(snr)... to ber(:, snr) = err/10^6;.

Body:
As I understand the ber matrix is not matching with err. Need help to overcome the error in the following code:

for snr= 1:50
err=0;
ber = err;
No= 1/10^(snr/10);
    for i= 1: 10^6;
        x= sign (randn(2,1));
        h= randn (1,2) * sqrt(1/2) + sqrt (1/2)* 1j* randn(1,2);
        w= sqrt(No/2)* randn (1,2) + sqrt(No/2)*1j* randn(1,2);
        alamh=[ h(1) h(2); conj(h(2)) -conj(h(1))];
        y= alamh * x + transpose(w);
        h_pseudoinverse= inv(ctranspose(alamh)* alamh)\ ctranspose(alamh);
        r= x + h_pseudoinverse * transpose (w);
        est_x= sign(real(r));
        err= (est_x~=x)+err;
    end
ber(snr)= err/10^6;
end

semilogy (1:50, ber,'-O')

Error:

Error: A(:) = B, the number of elements in A and B must be the same


问:
Difference between onLoad and ng-init in angular
I am learning angular. I don't understand what is difference between onLoad and ng-init for initialization of a variable. In which scope it creates this variable.

For example

```<code><ng-include onLoad="selectedReq=reqSelected" src="'partials/abc.html'"></ng-include>
</code>```

OR

```<code><ng-include ng-init="selectedReq=reqSelected" src="partials/abc.html"></ng-include>
</code>```

Please also give me some idea about isolated scope.

答:
Works for me.</p>

```<code><div ng-show="$scope.showme === true">Hello World</div>
<div ng-repeat="a in $scope.bigdata" ng-init="$scope.showme = true">{{ a.title }}</div>
</code>```

Body:
I am learning angular. I don't understand what is difference between onLoad and ng-init for initialization of a variable. In which scope it creates this variable.

For example

<ng-include onLoad="selectedReq=reqSelected" src="'partials/abc.html'"></ng-include>

OR

<ng-include ng-init="selectedReq=reqSelected" src="partials/abc.html"></ng-include>

Please also give me some idea about isolated scope.

Body:
Works for me.

<div ng-show="$scope.showme === true">Hello World</div>
<div ng-repeat="a in $scope.bigdata" ng-init="$scope.showme = true">{{ a.title }}</div>


问:
Coldfusion SOAP Exception Error Handling
How can I customize a SOAP error message in ColdFusion? Most languages like PHP, Java, .NET etc. have this capability. While I've seen this question asked on other sites, none of the threads contained an answer. If this isn't possible, I think Adobe should add a patch to support this feature.

Here is an example of the SOAP error in ColdFusion:

SOAP Request:

```<code><soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Header/>
   <soapenv:Body>

   </soapenv:Body>
</soapenv:Envelope>
</code>```

SOAP Response:

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soapenv:Body>
      <soapenv:Fault>
         <faultcode>soapenv:Server.userException</faultcode>
         <faultstring>java.lang.Exception: Body not found.</faultstring>
         <detail>
            <ns1:stackTrace xmlns:ns1="http://xml.apache.org/axis/">java.lang.Exception: Body not found.
                at org.apache.axis.providers.java.RPCProvider.processMessage(RPCProvider.java:121)
                ...</ns1:stackTrace>
            <ns2:hostname xmlns:ns2="http://xml.apache.org/axis/">Coldfusion Error</ns2:hostname>
         </detail>
      </soapenv:Fault>
   </soapenv:Body>
</soapenv:Envelope>
</code>```

In other languages you can customize the error message like so:

SOAP Response:

```<code> <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soapenv:Body>
      <soapenv:Fault>
         <faultcode>BODY_NOT_FOUND</faultcode>
         <faultstring>Body is missing in your request</faultstring>

      </soapenv:Fault>
   </soapenv:Body>
 </soapenv:Envelope>
</code>```

But I haven't found a way to achieve this in ColdFusion. We are planning to upgrade to ColdFusion 11. Does ColdFusion 11 (or below) have a way to do this?

答:
I would need to know how the application is generating and receiving requests to begin with.  With ColdFusion, to create a request, you would start by creating the SOAP Packet you want to send:

```<code><cfsavecontent variable = "variable name">
    <XML></XML>
</cfsavecontent>
</code>```

Next, use CFHTTP to send your SOAP request out:

https://help.adobe.com/en_US/ColdFusion/9.0/CFMLRef/WSc3ff6d0ea77859461172e0811cbec22c24-7ffc.html

When your response comes back and you have assigned it to a variable (set up in your CFHTTP request) you can use this response variable to determine how to parse the response.  So for example, you might use XMLParse or XMLSearch to find the elements and process them.

See:

https://helpx.adobe.com/coldfusion/cfml-reference/coldfusion-functions/functions-by-category/xml-functions.html

Note that special configuration might be required if network protocols are to be observed - for instance, SSLv3/TLS.  Consult your network administrator to determine if any configuration of ColdFusion needs to be done to support network architecture.  Also validate that your endpoints can see each other through any firewalls.  For more connection information consult either the ColdFusion documentation or threads relevant to your situation such as:

Does cfhttp for coldfusion 10 only supports up to TLS 1.0?

Body:
How can I customize a SOAP error message in ColdFusion? Most languages like PHP, Java, .NET etc. have this capability. While I've seen this question asked on other sites, none of the threads contained an answer. If this isn't possible, I think Adobe should add a patch to support this feature.

Here is an example of the SOAP error in ColdFusion:

SOAP Request:

<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Header/>
   <soapenv:Body>

   </soapenv:Body>
</soapenv:Envelope>

SOAP Response:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soapenv:Body>
      <soapenv:Fault>
         <faultcode>soapenv:Server.userException</faultcode>
         <faultstring>java.lang.Exception: Body not found.</faultstring>
         <detail>
            <ns1:stackTrace xmlns:ns1="http://xml.apache.org/axis/">java.lang.Exception: Body not found.
                at org.apache.axis.providers.java.RPCProvider.processMessage(RPCProvider.java:121)
                ...</ns1:stackTrace>
            <ns2:hostname xmlns:ns2="http://xml.apache.org/axis/">Coldfusion Error</ns2:hostname>
         </detail>
      </soapenv:Fault>
   </soapenv:Body>
</soapenv:Envelope>

In other languages you can customize the error message like so:

SOAP Response:

 <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soapenv:Body>
      <soapenv:Fault>
         <faultcode>BODY_NOT_FOUND</faultcode>
         <faultstring>Body is missing in your request</faultstring>

      </soapenv:Fault>
   </soapenv:Body>
 </soapenv:Envelope>

But I haven't found a way to achieve this in ColdFusion. We are planning to upgrade to ColdFusion 11. Does ColdFusion 11 (or below) have a way to do this?

Body:
I would need to know how the application is generating and receiving requests to begin with.  With ColdFusion, to create a request, you would start by creating the SOAP Packet you want to send:

<cfsavecontent variable = "variable name">
    <XML></XML>
</cfsavecontent>

Next, use CFHTTP to send your SOAP request out:

https://help.adobe.com/en_US/ColdFusion/9.0/CFMLRef/WSc3ff6d0ea77859461172e0811cbec22c24-7ffc.html

When your response comes back and you have assigned it to a variable (set up in your CFHTTP request) you can use this response variable to determine how to parse the response.  So for example, you might use XMLParse or XMLSearch to find the elements and process them.

See:

https://helpx.adobe.com/coldfusion/cfml-reference/coldfusion-functions/functions-by-category/xml-functions.html

Note that special configuration might be required if network protocols are to be observed - for instance, SSLv3/TLS.  Consult your network administrator to determine if any configuration of ColdFusion needs to be done to support network architecture.  Also validate that your endpoints can see each other through any firewalls.  For more connection information consult either the ColdFusion documentation or threads relevant to your situation such as:

Does cfhttp for coldfusion 10 only supports up to TLS 1.0?


问:
Wrong date when using SQL Server stored procedure with Dapper
I am using a stored procedure with Dapper to retrieve data from a table. The stored procedure works fine when executed in SQL Server and returns the required information.

But when I use Dapper to run the stored procedure and retrieve a Date, the Date is returned as 01/01/0001.

Here is my stored procedure  which works perfectly in SQL Server:

```<code>ALTER PROCEDURE [dbo].[spRankings_GetByEventAndGender]
   @Event varchar(50),
   @Gender varchar(10)
AS
BEGIN
    DECLARE @event_factor INT = CASE
                                   WHEN @Event IN ('Javelin', 'Discus', 'Shot Put', 'Hammer', 'Long Jump', 'High Jump', 'Triple Jump', 'Pole Vault')
                                      THEN -1 /* reverse ranking = highest value is best */
                                      ELSE 1  /* normal ranking = lowest value is best */
                                END;

    SELECT
        CASE
           WHEN a.mark = ABS(b.mark)
              THEN CAST(b.rank AS VARCHAR)
              ELSE ''
        END AS [Rank],
        /*
         ,a.athleteid
         ,a.teamid
         ,a.eventid
        */
        CASE
           WHEN @event_factor = -1
              THEN LTRIM(STR(a.mark, 10, 2))
              ELSE FORMAT(DATEADD(SECOND, FLOOR(a.mark), 0),case when a.mark<60 then '' else 'm:' end+'ss')
                 +substring(ltrim((str(cast(a.mark as decimal(12,5))%1,10,2))),2,10)
          end as Mark
         ,a.wind as Wind
         ,d.eventname as [Event]
         ,c.firstname+' '+c.lastname as Athlete
         --,Convert(varchar(10),c.BirthDate,103) as [Birth Date]
         ,c.BirthDate as [BirthDate]

         ,e.teamname as [Team]
         ,a.venue as Venue
         --, Convert(varchar(10),a.PerformanceDate,103) as [Performance Date]
         ,a.PerformanceDate as [Performance Date]
     from dbo.Performances as a
          inner join (select a.PersonId
                            ,a.eventid
                            ,min(a.mark*@event_factor) as mark
                            ,rank() over(partition by a.eventid order by min(a.mark*@event_factor)) as [rank]
                            ,avg(a.mark) as avg_mark
                        from dbo.Performances as a
                             inner join dbo.Persons as b
                                     on b.PersonId=a.PersonId
                             inner join dbo.[Events] as c
                                     on c.eventid=a.eventid
                             inner join dbo.Meets as d
                                    on d.MeetId = a.MeetId
                       where b.gender=@Gender
                         and c.eventname=@Event
                       group by a.PersonId
                               ,a.eventid
                     ) as b
                  on b.eventid=a.eventid
                 and b.PersonId=a.PersonId
          inner join dbo.Persons as c
                  on c.PersonId=a.PersonId
          inner join dbo.events as d
                  on d.eventid=a.eventid
          inner join dbo.teams as e
                  on e.teamid=a.teamid
            inner join dbo.Meets as m
                on m.MeetId = a.MeetId

    order by a.eventid
            ,a.mark*@event_factor
            ,b.[rank]
/*
            ,b.avg_mark
            ,a.athleteid
*/
end
</code>```

The results in SQL Server:

The method that uses Dapper to get the results:

```<code>public List<RankingsModel> GetRankingsByEventAndGender(string eventName, string gender) {
    using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(Helper.GetConString("GARanks"))) {
        var output = connection.Query<RankingsModel>($"dbo.spRankings_GetByEventAndGender @Event, @Gender", new { Event=eventName, Gender=gender}).ToList();
        return output;
    }
}
</code>```

The results in my application:

答:
You are getting the default value in the application. Please find below links which can help:

Date is 01/01/0001 and not the date that is in the database?

DateTime shows the date as 01/01/0001

HTH

Thanks.

Body:
I am using a stored procedure with Dapper to retrieve data from a table. The stored procedure works fine when executed in SQL Server and returns the required information.

But when I use Dapper to run the stored procedure and retrieve a Date, the Date is returned as 01/01/0001.

Here is my stored procedure  which works perfectly in SQL Server:

ALTER PROCEDURE [dbo].[spRankings_GetByEventAndGender]
   @Event varchar(50),
   @Gender varchar(10)
AS
BEGIN
    DECLARE @event_factor INT = CASE
                                   WHEN @Event IN ('Javelin', 'Discus', 'Shot Put', 'Hammer', 'Long Jump', 'High Jump', 'Triple Jump', 'Pole Vault')
                                      THEN -1 /* reverse ranking = highest value is best */
                                      ELSE 1  /* normal ranking = lowest value is best */
                                END;

    SELECT
        CASE
           WHEN a.mark = ABS(b.mark)
              THEN CAST(b.rank AS VARCHAR)
              ELSE ''
        END AS [Rank],
        /*
         ,a.athleteid
         ,a.teamid
         ,a.eventid
        */
        CASE
           WHEN @event_factor = -1
              THEN LTRIM(STR(a.mark, 10, 2))
              ELSE FORMAT(DATEADD(SECOND, FLOOR(a.mark), 0),case when a.mark<60 then '' else 'm:' end+'ss')
                 +substring(ltrim((str(cast(a.mark as decimal(12,5))%1,10,2))),2,10)
          end as Mark
         ,a.wind as Wind
         ,d.eventname as [Event]
         ,c.firstname+' '+c.lastname as Athlete
         --,Convert(varchar(10),c.BirthDate,103) as [Birth Date]
         ,c.BirthDate as [BirthDate]

         ,e.teamname as [Team]
         ,a.venue as Venue
         --, Convert(varchar(10),a.PerformanceDate,103) as [Performance Date]
         ,a.PerformanceDate as [Performance Date]
     from dbo.Performances as a
          inner join (select a.PersonId
                            ,a.eventid
                            ,min(a.mark*@event_factor) as mark
                            ,rank() over(partition by a.eventid order by min(a.mark*@event_factor)) as [rank]
                            ,avg(a.mark) as avg_mark
                        from dbo.Performances as a
                             inner join dbo.Persons as b
                                     on b.PersonId=a.PersonId
                             inner join dbo.[Events] as c
                                     on c.eventid=a.eventid
                             inner join dbo.Meets as d
                                    on d.MeetId = a.MeetId
                       where b.gender=@Gender
                         and c.eventname=@Event
                       group by a.PersonId
                               ,a.eventid
                     ) as b
                  on b.eventid=a.eventid
                 and b.PersonId=a.PersonId
          inner join dbo.Persons as c
                  on c.PersonId=a.PersonId
          inner join dbo.events as d
                  on d.eventid=a.eventid
          inner join dbo.teams as e
                  on e.teamid=a.teamid
            inner join dbo.Meets as m
                on m.MeetId = a.MeetId

    order by a.eventid
            ,a.mark*@event_factor
            ,b.[rank]
/*
            ,b.avg_mark
            ,a.athleteid
*/
end

The results in SQL Server:

The method that uses Dapper to get the results:

public List<RankingsModel> GetRankingsByEventAndGender(string eventName, string gender) {
    using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(Helper.GetConString("GARanks"))) {
        var output = connection.Query<RankingsModel>($"dbo.spRankings_GetByEventAndGender @Event, @Gender", new { Event=eventName, Gender=gender}).ToList();
        return output;
    }
}

The results in my application:


问:
NSClassFromString return nil for Bundle.main.infoDictionary
I am implementing my UITabBarController programmaticaly and I have an error when trying to retrieve my controllers from Bundle.main.infoDictionary!["CFBundleExecutable"]

Here is the code of the UITabBarController:

```<code>import UIKit

class ENTabBarController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        addChildViewControllers()
    }

    fileprivate func addChildViewControllers() {
        addChildViewController("ENSwipeViewController", imageName: "TabBar_swipe_")
        addChildViewController("ENSocialViewController", imageName: "TabBar_social_")
        addChildViewController("ENNotificationViewController", imageName: "TabBar_notification_")

    }

    fileprivate func addChildViewController(_ childControllerName: String, imageName: String) {
        let ns = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String

        let cls: AnyClass? = NSClassFromString(ns + "." + childControllerName)

        let vcClass = cls as! UIViewController.Type
        let vc = vcClass.init()

        vc.tabBarItem.image = UIImage(named: imageName)
        vc.tabBarItem.selectedImage = UIImage(named: imageName + "selected")

        let nav = UINavigationController()
        nav.addChildViewController(vc)
        addChildViewController(nav)
    }
}
</code>```

Error happens at let vcClass = cls as! UIViewController.Type and is:

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an
  Optional value

Here is the simple code of the ENSwipeViewController:

```<code>import UIKit

class ENSwipeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .red
    }
}
</code>```

答:
Your error is caused by attempting to force unwrap the optional value cls. Which is type AnyObject.type So, Adding the following lines of code to your func will fix your issue.

addChildViewController

```<code>let vcClassArray: [UIViewController.Type] = [
    ENSwipeViewController.self
]
let vcClass = classArray[0] // we only have one value
                        // if you have more you could simply make this a variable
let vc = vcClass.init()
</code>```

These lines above replace what you have here in the same func.

```<code>let vcClass = cls as! UIViewController.Type
let vc = vcClass.init()
</code>```

You will need to convert the AnyClass?to the Class you are segueing to and init using vcClass.init()

Body:
I am implementing my UITabBarController programmaticaly and I have an error when trying to retrieve my controllers from Bundle.main.infoDictionary!["CFBundleExecutable"]

Here is the code of the UITabBarController:

import UIKit

class ENTabBarController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        addChildViewControllers()
    }

    fileprivate func addChildViewControllers() {
        addChildViewController("ENSwipeViewController", imageName: "TabBar_swipe_")
        addChildViewController("ENSocialViewController", imageName: "TabBar_social_")
        addChildViewController("ENNotificationViewController", imageName: "TabBar_notification_")

    }

    fileprivate func addChildViewController(_ childControllerName: String, imageName: String) {
        let ns = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String

        let cls: AnyClass? = NSClassFromString(ns + "." + childControllerName)

        let vcClass = cls as! UIViewController.Type
        let vc = vcClass.init()

        vc.tabBarItem.image = UIImage(named: imageName)
        vc.tabBarItem.selectedImage = UIImage(named: imageName + "selected")

        let nav = UINavigationController()
        nav.addChildViewController(vc)
        addChildViewController(nav)
    }
}

Error happens at let vcClass = cls as! UIViewController.Type and is:

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an
  Optional value

Here is the simple code of the ENSwipeViewController:

import UIKit

class ENSwipeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .red
    }
}

Body:
Your error is caused by attempting to force unwrap the optional value cls. Which is type AnyObject.type So, Adding the following lines of code to your func will fix your issue.

addChildViewController

let vcClassArray: [UIViewController.Type] = [
    ENSwipeViewController.self
]
let vcClass = classArray[0] // we only have one value
                        // if you have more you could simply make this a variable
let vc = vcClass.init()

These lines above replace what you have here in the same func.

let vcClass = cls as! UIViewController.Type
let vc = vcClass.init()

You will need to convert the AnyClass?to the Class you are segueing to and init using vcClass.init()


问:
Subclass or Protocol, How to?
I'm developing an iOS application where I have a screen which displays some filters for a related search. Now I've made all of these filters as custom UIViews because they all have fairly different UI and they have to be reused on different screens. Inspite of their differences they all present a common interface to the View Controller managing them, so the view controller isn't concerned with what and how a filterView does something. It's only concerned with passing some data to them and retrieving their state through a property common to all of them. They all have their different classes which are subclasses of FilterView a subclass of UIView. This FilterView class presents an interface which all of these subclasses adopt.

This methodology works fine, but the problem is that all of the methods and properties a filterView should present are declared in the base class FilterView and if some particular filter doesn't implement a behavior it defaults to the behavior provided by its superclass FilterView. I don't want this. I want that every FilterView subclass should be required to provide an implementation on the FilterView API or otherwise provide their own defaults not the defaults of a superclass.

If I use a protocol to implement this behavior I loose the ability for all these classes to compulsorily be UIViews which is also a requirement.

Can you suggest what design pattern should I use to better manage all the different FilterView subclasses.

答:
This can be expressed clearly now in swift 4 by defining the common interface in a protocol named Filter and then defining FilterView as:

```<code>typealias FilterView = UIView & Filter
</code>```

Title: Subclass or Protocol, How to?

Body:
This can be expressed clearly now in swift 4 by defining the common interface in a protocol named Filter and then defining FilterView as:

typealias FilterView = UIView & Filter


问:
how to get datetime to int in django? use datetime only hour and minute
I wanted to save the time as an int type so I could get the difference between the two times.

i import datetime and try to like this

```<code>now = datetime.now()
</code>```

but i get this : 2017-11-18 05:47:35.262111

how to get only hour and minute to int

ex) 0547

I could not solve it.

答:
Use the hour and minute attributes and cast them to integer. </p>

```<code> import datetime
    hour_now = int(datetime.datetime.now().hour) # for hour
    minute_now = int(datetime.datetime.now().minute) # for minute
</code>```

Body:
I wanted to save the time as an int type so I could get the difference between the two times.

i import datetime and try to like this

now = datetime.now()

but i get this : 2017-11-18 05:47:35.262111

how to get only hour and minute to int

ex) 0547

I could not solve it.

Body:
Use the hour and minute attributes and cast them to integer.

 import datetime
    hour_now = int(datetime.datetime.now().hour) # for hour
    minute_now = int(datetime.datetime.now().minute) # for minute


问:
Kafka topic not being deleted
I am using Kafka 0.10.0.1. There are 3 brokers in the cluster. I issued delete command to delete nearly 10 topics which were not getting used since a month. I had checked, there are no consumers registered on those topics, nor were their log sizes increasing. </p>

<p>However, it's been more than 5 hours and those topics haven't yet been deleted. They are just marked for deletion. What can be the reason? </p>

答:
extending to Mickael answer

In Kafka 0.10, default value of delete.topic.enable is false.

When using the command-line tools to delete a topic, a Zookeeper node requests that the deletion is created. Under normal circumstances, this is executed by the cluster immediately. However, the command-line tool has no way of knowing whether topic deletion is enabled in the cluster. As a result, it will request deletion of topics regardless, which can result in a surprise if deletion is disabled.

Topics are requested for deletion by creating a Zookeeper node as a child under /admin/delete_topic, which is named with the topic name. a new thread will invoke and check topic deletion is enabled or not. if enabled it will delete all logs and paths in zookeeper

if deletion is not enabled we have to manually delete all the configs of topic

steps to remove topic manually :

Shut down all brokers in the cluster

Remove the Zookeeper path /brokers/topics/TOPICNAME from the Kafka cluster path. Note that this node has child nodes that must be deleted first.

Remove the partition directories from the log directories on each broker. These will be named TOPICNAME-NUM, where NUM is the partition ID.

Restart all brokers

Title: Kafka topic not being deleted

Body:
I am using Kafka 0.10.0.1. There are 3 brokers in the cluster. I issued delete command to delete nearly 10 topics which were not getting used since a month. I had checked, there are no consumers registered on those topics, nor were their log sizes increasing.

However, it's been more than 5 hours and those topics haven't yet been deleted. They are just marked for deletion. What can be the reason?


问:
How to combine multiple arrays with same amount of items in php
Is there a way to combine multiple arrays with same amount of items? See below the 4 arrays with 5 items inside:

```<code>$type = array('Type 1','Type 2','Type 3',' Type 4','Type 5');
$desc = array('Description 1','Description 2','Description 3','Description 4','Description 5');
$brand = array('Brand 1','Brand 2','Brand 3','Brand 4','Brand 5');
$model = array('Model 1','Model 2','Model 3','Model 4','Model 5');
</code>```

Expected Results:

```<code>[0] => Array
    (
        [0] => Type 1
        [1] => Description 1
        [2] => Brand 1
        [3] => Model 1
    )

[1] => Array
    (
        [0] => Type 2
        [1] => Description 2
        [2] => Brand 2
        [3] => Model 2
    )

[2] => Array
    (
        [0] => Type 3
        [1] => Description 3
        [2] => Brand 3
        [3] => Model 3
    )

[3] => Array
    (
        [0] => Type 4
        [1] => Description 4
        [2] => Brand 4
        [3] => Model 4
    )

[4] => Array
    (
        [0] => Type 5
        [1] => Description 5
        [2] => Brand 5
        [3] => Model 5
    )
</code>```

I'm not PHP expert please help me :)

Thank you.

答:
Try this code :</p>

```<code>$type = array('Type 1','Type 2','Type 3',' Type 4','Type 5');
$desc = array('Description 1','Description 2','Description 3','Description 4','Description 5');
$brand = array('Brand 1','Brand 2','Brand 3','Brand 4','Brand 5');
$model = array('Model 1','Model 2','Model 3','Model 4','Model 5');

$result = array();
foreach($type as $key=>$val){ // Loop though one array
    $val2 = $desc[$key];
    $val3 = $brand[$key];
    $val4 = $model[$key];
    $result[$key] =array($val,$val2, $val3,$val4);
}

print_r($result);
</code>```

Body:
Is there a way to combine multiple arrays with same amount of items? See below the 4 arrays with 5 items inside:

$type = array('Type 1','Type 2','Type 3',' Type 4','Type 5');
$desc = array('Description 1','Description 2','Description 3','Description 4','Description 5');
$brand = array('Brand 1','Brand 2','Brand 3','Brand 4','Brand 5');
$model = array('Model 1','Model 2','Model 3','Model 4','Model 5');

Expected Results:

[0] => Array
    (
        [0] => Type 1
        [1] => Description 1
        [2] => Brand 1
        [3] => Model 1
    )

[1] => Array
    (
        [0] => Type 2
        [1] => Description 2
        [2] => Brand 2
        [3] => Model 2
    )

[2] => Array
    (
        [0] => Type 3
        [1] => Description 3
        [2] => Brand 3
        [3] => Model 3
    )

[3] => Array
    (
        [0] => Type 4
        [1] => Description 4
        [2] => Brand 4
        [3] => Model 4
    )

[4] => Array
    (
        [0] => Type 5
        [1] => Description 5
        [2] => Brand 5
        [3] => Model 5
    )

I'm not PHP expert please help me :)

Thank you.

Body:
Try this code :

$type = array('Type 1','Type 2','Type 3',' Type 4','Type 5');
$desc = array('Description 1','Description 2','Description 3','Description 4','Description 5');
$brand = array('Brand 1','Brand 2','Brand 3','Brand 4','Brand 5');
$model = array('Model 1','Model 2','Model 3','Model 4','Model 5');

$result = array();
foreach($type as $key=>$val){ // Loop though one array
    $val2 = $desc[$key];
    $val3 = $brand[$key];
    $val4 = $model[$key];
    $result[$key] =array($val,$val2, $val3,$val4);
}

print_r($result);


问:
Can't create Windows Service that references .NET Core 2.0 assemblies
I need a non-ASPNET Windows Service (like old style console app).  I know that I can't create a Windows Service in Visual Studio (.NET Framework only) and reference any Core 1/2 assemblies; not allowed.

I want to leverage all the work my other ASPNET projects like database repositories...that are already in Core 2.0.

So...any ideas how I can write a Windows Service that somehow leverages work created in Core Visual Studio projects?

Reference: Another post on this topic.

答:
Update to the Answer

Based on the Martin's answer  and comment Now you can use  Windows Compatibility Pack for the purpose.

Yes,a netcoreapp can not be referenced by net framework project. This document at https://github.com/dotnet/standard/blob/master/docs/versions.md shows the compatibility matrix. According to that net framework can only refer to compatible netstandard projects.

And further according to Api reference for ServiceBase Class , ServiceBase class is available only in net framework.

One option comes in to my mind to leverage netcoreapp projects in a windows services is creating a multi target project with netcore2.0 and net471 or make the coreapp project a multi target, with conditional compilation.

Add a conditional reference to Microsoft.AspNetCore.Hosting.WindowsServices in csproj. Then conditionally call host.RunAsService and host.Run in program.cs.

For more info about multi target   and windows services please have a look at

How to Multitarget section in Developing Libraries with cross platform tools

Host an ASP.NET Core app in a Windows Service


问:
Only the SeekBar in last item of RecyclerView is working
I am trying to create an app where I am using RecyclerView to show/play list of audio which is to be streamed. Each item in the  RecyclerView has a SeekBar, a button, and TextView for audio timer.

The problem I am facing is that when I play the audio, the seekbar is running only for the last item of the RecyclerView. I have seen similar other problems but have not been able to solve mine. Here is the code I am using for the Adapter:

```<code>public class AudioAdapter extends RecyclerView.Adapter<AudioAdapter.ViewHolder> {
Context context;
LayoutInflater inflator;
ArrayList<AudioModel> list = new ArrayList();
SeekBar mSeekBar;
TextView mTvAudioLength;
MediaPlayer mMediaPlayer;

public AudioAdapter(Context context, ArrayList<AudioModel> list) {
    this.context = context;
    this.list = list;
    inflator = LayoutInflater.from(context);
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = inflator.inflate(R.layout.audio_recyclerview_layout, parent, false);
    AudioAdapter.ViewHolder viewHolder = new AudioAdapter.ViewHolder(view);
    return viewHolder;
}

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {

    final AudioModel modelList = list.get(position);
    //holder.tvAudioLength.setText(modelList.duration);
    holder.tvAudioName.setText(modelList.name);

    // Initializing MediaPlayer
    final MediaPlayer mediaPlayer = new MediaPlayer();

    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    try {
        mediaPlayer.setDataSource(modelList.url);
        mediaPlayer.prepare();// might take long for buffering.
    } catch (IOException e) {
        e.printStackTrace();
    }
    mMediaPlayer = mediaPlayer;
    mTvAudioLength = holder.tvAudioLength;
    mSeekBar = holder.seekBar;
    holder.seekBar.setMax(mediaPlayer.getDuration());
    run.run();
    holder.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (mediaPlayer != null && fromUser) {
                mediaPlayer.seekTo(progress);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });
    holder.tvAudioLength.setText(calculateDuration(mediaPlayer.getDuration()));
    holder.btn_play.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (!mediaPlayer.isPlaying()) {
                mediaPlayer.start();
                holder.btn_play.setText("Pause");
            } else {
                mediaPlayer.pause();
                holder.btn_play.setText("Play");
            }
        }
    });
}
Runnable run = new Runnable() {
    @Override
    public void run() {
        // Updateing SeekBar every 100 miliseconds
        Handler seekHandler = new Handler();
        mSeekBar.setProgress(mMediaPlayer.getCurrentPosition());
        seekHandler.postDelayed(run, 100);
        //For Showing time of audio(inside runnable)
        int miliSeconds = mMediaPlayer.getCurrentPosition();
        if(miliSeconds!=0) {
            //if audio is playing, showing current time;
            long minutes = TimeUnit.MILLISECONDS.toMinutes(miliSeconds);
            long seconds = TimeUnit.MILLISECONDS.toSeconds(miliSeconds);
            if (minutes == 0) {
                mTvAudioLength.setText("0:" + seconds);
            } else {
                if (seconds >= 60) {
                    long sec = seconds - (minutes * 60);
                    mTvAudioLength.setText(minutes + ":" + sec);
                }
            }
        }else{
            //Displaying total time if audio not playing
            int totalTime=mMediaPlayer.getDuration();
            long minutes = TimeUnit.MILLISECONDS.toMinutes(totalTime);
            long seconds = TimeUnit.MILLISECONDS.toSeconds(totalTime);
            if (minutes == 0) {
                mTvAudioLength.setText("0:" + seconds);
            } else {
                if (seconds >= 60) {
                    long sec = seconds - (minutes * 60);
                    mTvAudioLength.setText(minutes + ":" + sec);
                }
            }
        }
    }

};

@Override
public int getItemCount() {
    return list.size();
}

class ViewHolder extends RecyclerView.ViewHolder {
    Button btn_play;
    TextView tvAudioLength;
    TextView tvAudioName;
    SeekBar seekBar;

    public ViewHolder(View itemView) {
        super(itemView);
       // mTvAudioLength =(TextView) itemView.findViewById(R.id.tv_audio_lenght);
       // mSeekBar = (SeekBar) itemView.findViewById(R.id.seekBar);
        btn_play = (Button) itemView.findViewById(R.id.btn_play);
        tvAudioLength = (TextView) itemView.findViewById(R.id.tv_audio_lenght);
        tvAudioName = (TextView) itemView.findViewById(R.id.tv_audio_name);
        seekBar = (SeekBar) itemView.findViewById(R.id.seekBar);
        //seekBar.setTag(itemView.findViewById(R.id.seekBar));
    }
}

private String calculateDuration(int duration) {
    String finalDuration = "";
    long minutes = TimeUnit.MILLISECONDS.toMinutes(duration);
    long seconds = TimeUnit.MILLISECONDS.toSeconds(duration);
    if (minutes == 0) {
        finalDuration = "0:" + seconds;
    } else {
        if (seconds >= 60) {
            long sec = seconds - (minutes * 60);
            finalDuration = minutes + ":" + sec;
        }
    }
    return finalDuration;
}
</code>```

}

Image of the Layout

答: You have created a runnable. So a new thread is created to update your seekbar. In that thread you have use mSeekBar.setProgress(mMediaPlayer.getCurrentPosition()); to update progress which is not synchronized with mail thread. While executing each item view a separate thread is created and mSeekbar instance does not retain the proper instance(i.e) when a new view is created a new thread created and mSeekbar get new instance. Finally, the last instance of seekbar assigned to mSeekbar. So updation takes place only in last seek bar. Why did you create another runnable for progress bar update?

Body:
I am trying to create an app where I am using RecyclerView to show/play list of audio which is to be streamed. Each item in the  RecyclerView has a SeekBar, a button, and TextView for audio timer.

The problem I am facing is that when I play the audio, the seekbar is running only for the last item of the RecyclerView. I have seen similar other problems but have not been able to solve mine. Here is the code I am using for the Adapter:

public class AudioAdapter extends RecyclerView.Adapter<AudioAdapter.ViewHolder> {
Context context;
LayoutInflater inflator;
ArrayList<AudioModel> list = new ArrayList();
SeekBar mSeekBar;
TextView mTvAudioLength;
MediaPlayer mMediaPlayer;

public AudioAdapter(Context context, ArrayList<AudioModel> list) {
    this.context = context;
    this.list = list;
    inflator = LayoutInflater.from(context);
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = inflator.inflate(R.layout.audio_recyclerview_layout, parent, false);
    AudioAdapter.ViewHolder viewHolder = new AudioAdapter.ViewHolder(view);
    return viewHolder;
}

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {

    final AudioModel modelList = list.get(position);
    //holder.tvAudioLength.setText(modelList.duration);
    holder.tvAudioName.setText(modelList.name);

    // Initializing MediaPlayer
    final MediaPlayer mediaPlayer = new MediaPlayer();

    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    try {
        mediaPlayer.setDataSource(modelList.url);
        mediaPlayer.prepare();// might take long for buffering.
    } catch (IOException e) {
        e.printStackTrace();
    }
    mMediaPlayer = mediaPlayer;
    mTvAudioLength = holder.tvAudioLength;
    mSeekBar = holder.seekBar;
    holder.seekBar.setMax(mediaPlayer.getDuration());
    run.run();
    holder.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (mediaPlayer != null && fromUser) {
                mediaPlayer.seekTo(progress);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });
    holder.tvAudioLength.setText(calculateDuration(mediaPlayer.getDuration()));
    holder.btn_play.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (!mediaPlayer.isPlaying()) {
                mediaPlayer.start();
                holder.btn_play.setText("Pause");
            } else {
                mediaPlayer.pause();
                holder.btn_play.setText("Play");
            }
        }
    });
}
Runnable run = new Runnable() {
    @Override
    public void run() {
        // Updateing SeekBar every 100 miliseconds
        Handler seekHandler = new Handler();
        mSeekBar.setProgress(mMediaPlayer.getCurrentPosition());
        seekHandler.postDelayed(run, 100);
        //For Showing time of audio(inside runnable)
        int miliSeconds = mMediaPlayer.getCurrentPosition();
        if(miliSeconds!=0) {
            //if audio is playing, showing current time;
            long minutes = TimeUnit.MILLISECONDS.toMinutes(miliSeconds);
            long seconds = TimeUnit.MILLISECONDS.toSeconds(miliSeconds);
            if (minutes == 0) {
                mTvAudioLength.setText("0:" + seconds);
            } else {
                if (seconds >= 60) {
                    long sec = seconds - (minutes * 60);
                    mTvAudioLength.setText(minutes + ":" + sec);
                }
            }
        }else{
            //Displaying total time if audio not playing
            int totalTime=mMediaPlayer.getDuration();
            long minutes = TimeUnit.MILLISECONDS.toMinutes(totalTime);
            long seconds = TimeUnit.MILLISECONDS.toSeconds(totalTime);
            if (minutes == 0) {
                mTvAudioLength.setText("0:" + seconds);
            } else {
                if (seconds >= 60) {
                    long sec = seconds - (minutes * 60);
                    mTvAudioLength.setText(minutes + ":" + sec);
                }
            }
        }
    }

};

@Override
public int getItemCount() {
    return list.size();
}

class ViewHolder extends RecyclerView.ViewHolder {
    Button btn_play;
    TextView tvAudioLength;
    TextView tvAudioName;
    SeekBar seekBar;

    public ViewHolder(View itemView) {
        super(itemView);
       // mTvAudioLength =(TextView) itemView.findViewById(R.id.tv_audio_lenght);
       // mSeekBar = (SeekBar) itemView.findViewById(R.id.seekBar);
        btn_play = (Button) itemView.findViewById(R.id.btn_play);
        tvAudioLength = (TextView) itemView.findViewById(R.id.tv_audio_lenght);
        tvAudioName = (TextView) itemView.findViewById(R.id.tv_audio_name);
        seekBar = (SeekBar) itemView.findViewById(R.id.seekBar);
        //seekBar.setTag(itemView.findViewById(R.id.seekBar));
    }
}

private String calculateDuration(int duration) {
    String finalDuration = "";
    long minutes = TimeUnit.MILLISECONDS.toMinutes(duration);
    long seconds = TimeUnit.MILLISECONDS.toSeconds(duration);
    if (minutes == 0) {
        finalDuration = "0:" + seconds;
    } else {
        if (seconds >= 60) {
            long sec = seconds - (minutes * 60);
            finalDuration = minutes + ":" + sec;
        }
    }
    return finalDuration;
}

}

Image of the Layout


问:
ERROR JAVA CODE correct it
```<code>//my code is on java code on employ details using console
//my input is no.of employess
//i am taking input a employ details
//function on searching for a given employ for a given id
</code>```

// code meaning
    // #String employee[][]=new String[numberOfEmployees][12];  will store //employ details
//#String input will take the employee  details in the string formatt.

//#String choice will take choice as yes to search the another employee

     /ABOVE CODE IS ON DEVELOPING SIMPLE JAVA CODE ON EMPLOY MANAGEMENT SYSTEM/

```<code>import java.util.Scanner;

public class EmployeeManagement {

    public static void main(String args[]){
        Scanner read=new Scanner(System.in);
        System.out.println("Enter  the no.of employees");
        int numberOfEmployees=read.nextInt();//GIVEN INPUT FOR NO.OF EMPLOYESS
        int employeeId;
        String employee[][]=new String[numberOfEmployees][12];
        for(int inner=0;inner<numberOfEmployees;inner++){/*taken input on employ details*/
            for(int outer=0;outer<11;outer++){
                employee[inner][outer]=read.nextLine();
            }
            System.out.println();
        }
        for(int inner=0;inner<numberOfEmployees;inner++){
                 employee[inner][11] = (int)(Integer.parseInt(employee[inner][5])+Integer.parseInt(employee[inner][6])
                                 +Integer.parseInt(employee[inner][7])+Integer.parseInt(employee[inner][8])
                                 -Integer.parseInt(employee[inner][9])-Integer.parseInt(employee[inner][10]));
                           }
        String choice;

                     do{
            System.out.println("do you want to search enter employee id");
            String input=read.nextLine();
            System.out.println("do you want to continue press yes or YES");
                        read.nextLine();
            choice =read.nextLine();
        }while(choice=="yes" || choice=="YES");
                     for(int inner=0;inner<numberOfEmployees;inner++){
            if(employee[inner][0]=="input"){
        for(int outer=0;outer<12;outer++)
            System.out.print(employee[inner][outer]);
                                                               }
        System.out.println();

         }

    }
}
</code>```

答:
If you format the code in the question properly it will be easier to see what's going wrong. But to start with:

Don't compare Strings like this:

```<code>choice=="yes"
</code>```

Then you just check if the first String object is the same object as the second one, and in this case they never are.

Instead, go like this:

```<code>choice.equals("yes")
</code>```

Or better yet, since you never risk a NullPointerException:

```<code>"yes".equals(choice)
</code>```

Title: ERROR JAVA CODE correct it

Body:
//my code is on java code on employ details using console
//my input is no.of employess
//i am taking input a employ details
//function on searching for a given employ for a given id

// code meaning
    // #String employee[][]=new String[numberOfEmployees][12];  will store //employ details
//#String input will take the employee  details in the string formatt.

//#String choice will take choice as yes to search the another employee

     /ABOVE CODE IS ON DEVELOPING SIMPLE JAVA CODE ON EMPLOY MANAGEMENT SYSTEM/

import java.util.Scanner;

public class EmployeeManagement {

    public static void main(String args[]){
        Scanner read=new Scanner(System.in);
        System.out.println("Enter  the no.of employees");
        int numberOfEmployees=read.nextInt();//GIVEN INPUT FOR NO.OF EMPLOYESS
        int employeeId;
        String employee[][]=new String[numberOfEmployees][12];
        for(int inner=0;inner<numberOfEmployees;inner++){/*taken input on employ details*/
            for(int outer=0;outer<11;outer++){
                employee[inner][outer]=read.nextLine();
            }
            System.out.println();
        }
        for(int inner=0;inner<numberOfEmployees;inner++){
                 employee[inner][11] = (int)(Integer.parseInt(employee[inner][5])+Integer.parseInt(employee[inner][6])
                                 +Integer.parseInt(employee[inner][7])+Integer.parseInt(employee[inner][8])
                                 -Integer.parseInt(employee[inner][9])-Integer.parseInt(employee[inner][10]));
                           }
        String choice;

                     do{
            System.out.println("do you want to search enter employee id");
            String input=read.nextLine();
            System.out.println("do you want to continue press yes or YES");
                        read.nextLine();
            choice =read.nextLine();
        }while(choice=="yes" || choice=="YES");
                     for(int inner=0;inner<numberOfEmployees;inner++){
            if(employee[inner][0]=="input"){
        for(int outer=0;outer<12;outer++)
            System.out.print(employee[inner][outer]);
                                                               }
        System.out.println();

         }

    }
}

Body:
If you format the code in the question properly it will be easier to see what's going wrong. But to start with:

Don't compare Strings like this:

choice=="yes"

Then you just check if the first String object is the same object as the second one, and in this case they never are.

Instead, go like this:

choice.equals("yes")

Or better yet, since you never risk a NullPointerException:

"yes".equals(choice)


问:
Sum next array elements from a starting position (javascript)
I need this for dynamically use.
I have 2 associated arrays:

```<code>Var $some = [1, 2, 3];
Var $other = [a, b, c];
</code>```

a, b, c are some html ids and 1, 2, 3 are their values.
I want something like this on trigger:

```<code>$'#a').attr('max', //b+c val(2+3)
$'#b').attr('max', //a+c val(1+3)
$'#c').attr('max', //a+b val(1+2)
</code>```

I ve searched here get prev and next items in array about finding next elements in array, and I think would be usefull a loop that itinerate elements a (then b then c) with its values and for each one execute a code like: sum next elements to them. Substracting element value after sumed won't work pripperly because I want that script on some ranges change...
So...my question would be: how can I sum elements itinerated from a loop? I think that would be the key to solve this because I can loop it 2 times in this example and would stop without started element...

答:
Assuming that key of other is the same with it's corresponding value on some

const some = [1, 2, 3];
const other = [a, b, c];

$.each(other, function(key, value){                        // Loop thru each id
    var sum = some.reduce((x, y) => x + y) - some[key]; // add each 'some' elements and subtracting the id's value
    $(value).attr('max', sum);                             // set max attr of id equal to sum
});

// log output on console
console.log(a);
console.log(b);
console.log(c);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="number" id="a">
<input type="number" id="b">
<input type="number" id="c"></code>```

Body:
I need this for dynamically use.
I have 2 associated arrays:

Var $some = [1, 2, 3];
Var $other = [a, b, c];

a, b, c are some html ids and 1, 2, 3 are their values.
I want something like this on trigger:

$'#a').attr('max', //b+c val(2+3)
$'#b').attr('max', //a+c val(1+3)
$'#c').attr('max', //a+b val(1+2)

I ve searched here get prev and next items in array about finding next elements in array, and I think would be usefull a loop that itinerate elements a (then b then c) with its values and for each one execute a code like: sum next elements to them. Substracting element value after sumed won't work pripperly because I want that script on some ranges change...
So...my question would be: how can I sum elements itinerated from a loop? I think that would be the key to solve this because I can loop it 2 times in this example and would stop without started element...

Body:
Assuming that key of other is the same with it's corresponding value on some

const some = [1, 2, 3];
const other = [a, b, c];

$.each(other, function(key, value){                        // Loop thru each id
    var sum = some.reduce((x, y) => x + y) - some[key]; // add each 'some' elements and subtracting the id's value
    $(value).attr('max', sum);                             // set max attr of id equal to sum
});

// log output on console
console.log(a);
console.log(b);
console.log(c);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="number" id="a">
<input type="number" id="b">
<input type="number" id="c">


问:
Separation of directives into modules AngularJS
Someone answer on my very important question. :)

I has been working on various projects in angularjsfor several months.

I have problem of code breakdown on different structures, modules, directives.

Let's say I have a project which have,
- a top menu with a lot of functionality that repeats itself,
- side menu that contains a lot of functions
- board with lists and cards, the possibility of their transfer,
- Clicking on the card opens a modal window which also has a lot of functionality,

The frightening thing is that I have it all in one controller and in one htmltemplate. :D

And I thought that I would create separate directives also with separate controllers for each of these things.
Each directive will have:

directiv

```<code>restrict : 'E',
templateUrl,
controller: function() {}
controllerAs
</code>```

I heard that it is good to do so to separate the menu directive to a separate module.

Could someone tell me if I good thinking or not? If not Could someone tell me how to share it well? for what things?

Thanks !

答:
I have a few suggestions for you:

Split your html file into multiple components (or directives if you are using AngularJS < v1.5) by grouping your html into different sections. Create a component for each section like so:

```<code><body>

    <top-menu></top-menu>

    <sidebar></sidebar>

    <board></board>

</body>
</code>```

Notice how much simpler it is to immediately distinguish the major sections of your UI. Because your components are feature-rich, you can further break down each component into more subcomponents. For example, topMenu's template could be:

```<code><ul>
    <a>Link 1</a>
    <a>Link 2</a>
    <a>Link 3</a>
</ul>

<search-bar></search-bar>

<social-media></social-media>

<chat-box></chat-box>
</code>```

The added benefit is that you can now reuse searchBar, socialMedia, and chatBox throughout your application.

Because you mentioned that the topMenu, sidebar, and board all have rich functionality, you can organize the major features of your UI by placing each feature into its own module. You could have an app.topMenu module, app.sidebar module, and app.board module. You then declare these modules as dependencies in your main app module like so:

```<code>angular.module("app", [

    // Module that contains shared modules
    "app.common",

    // Feature-specific modules
    "app.topMenu",
    "app.sidebar",
    "app.board"
]);
</code>```

You can now group all of topMenu's private services and components into app.topMenu. For components/directives/modules/services that are shared across your application, you can place those in the app.common module.

Keep your controllers lean by outsourcing reusable logic into services that can be reused throughout your application. For example, if you are making ajax calls in your controllers, move that logic into AngularJS services so that different parts of your application can also make those ajax calls. This can really help keep your code DRY (don't repeat yourself) and maintainable.

For a more complete list on how you can structure and style various parts of your application, see John Papa's AngularJS style guide here.

Body:
Someone answer on my very important question. :)

I has been working on various projects in angularjsfor several months.

I have problem of code breakdown on different structures, modules, directives.

Let's say I have a project which have,
- a top menu with a lot of functionality that repeats itself,
- side menu that contains a lot of functions
- board with lists and cards, the possibility of their transfer,
- Clicking on the card opens a modal window which also has a lot of functionality,

The frightening thing is that I have it all in one controller and in one htmltemplate. :D

And I thought that I would create separate directives also with separate controllers for each of these things.
Each directive will have:

directiv

restrict : 'E',
templateUrl,
controller: function() {}
controllerAs

I heard that it is good to do so to separate the menu directive to a separate module.

Could someone tell me if I good thinking or not? If not Could someone tell me how to share it well? for what things?

Thanks !

Body:
I have a few suggestions for you:

Split your html file into multiple components (or directives if you are using AngularJS < v1.5) by grouping your html into different sections. Create a component for each section like so:

<body>

    <top-menu></top-menu>

    <sidebar></sidebar>

    <board></board>

</body>

Notice how much simpler it is to immediately distinguish the major sections of your UI. Because your components are feature-rich, you can further break down each component into more subcomponents. For example, topMenu's template could be:

<ul>
    <a>Link 1</a>
    <a>Link 2</a>
    <a>Link 3</a>
</ul>

<search-bar></search-bar>

<social-media></social-media>

<chat-box></chat-box>

The added benefit is that you can now reuse searchBar, socialMedia, and chatBox throughout your application.

Because you mentioned that the topMenu, sidebar, and board all have rich functionality, you can organize the major features of your UI by placing each feature into its own module. You could have an app.topMenu module, app.sidebar module, and app.board module. You then declare these modules as dependencies in your main app module like so:

angular.module("app", [

    // Module that contains shared modules
    "app.common",

    // Feature-specific modules
    "app.topMenu",
    "app.sidebar",
    "app.board"
]);

You can now group all of topMenu's private services and components into app.topMenu. For components/directives/modules/services that are shared across your application, you can place those in the app.common module.

Keep your controllers lean by outsourcing reusable logic into services that can be reused throughout your application. For example, if you are making ajax calls in your controllers, move that logic into AngularJS services so that different parts of your application can also make those ajax calls. This can really help keep your code DRY (don't repeat yourself) and maintainable.

For a more complete list on how you can structure and style various parts of your application, see John Papa's AngularJS style guide here.


问:
How do I prevent user from adding a duplicate entry into a MySQL database?
I am working on an inventory database program using Java. I wrote a method that adds new product and quantity to the database. I am stuck on how I can prevent user from adding a duplicate entry to the database.
If the user enters a name that already exists in the database, the program should display an error message and show the main menu again. The program should not ask the user to enter the data again. The program should not replace the existing entry.
Thanks in advance!</p>

```<code>public static void addData() {
    try (Connection conn = DriverManager.getConnection(db_url, user, password)) {

        String product = stringInput("Please enter the name of the product to store in inventory");
        int quantity = intInput("Please enter the quantity of the product");

        String addProduct = "INSERT INTO inventory VALUES (?,?)";
        PreparedStatement insertProduct = conn.prepareStatement(addProduct);

        insertProduct.setString(1, product);
        insertProduct.setInt(2, quantity);

        insertProduct.executeUpdate();
        conn.close();

        } catch(SQLException sqle){
            sqle.printStackTrace();
            System.exit(-1);
        }

    }
</code>```

答: In that case create a id column in your table and which should be unique or primary key. And handle exception  SQLIntegrityConstraintViolationException to show the error message on app display.

Body:
I am working on an inventory database program using Java. I wrote a method that adds new product and quantity to the database. I am stuck on how I can prevent user from adding a duplicate entry to the database.
If the user enters a name that already exists in the database, the program should display an error message and show the main menu again. The program should not ask the user to enter the data again. The program should not replace the existing entry.
Thanks in advance!

public static void addData() {
    try (Connection conn = DriverManager.getConnection(db_url, user, password)) {

        String product = stringInput("Please enter the name of the product to store in inventory");
        int quantity = intInput("Please enter the quantity of the product");

        String addProduct = "INSERT INTO inventory VALUES (?,?)";
        PreparedStatement insertProduct = conn.prepareStatement(addProduct);

        insertProduct.setString(1, product);
        insertProduct.setInt(2, quantity);

        insertProduct.executeUpdate();
        conn.close();

        } catch(SQLException sqle){
            sqle.printStackTrace();
            System.exit(-1);
        }

    }


问:
Automatically check or uncheck RecyclerView checkboxes with boolean values
I need to check my recyclerview checkboxes automatically based on boolean values coming from POJO class. below is my class details.

HealthStatusCheck.java:

```<code>public class HealthStatusCheck {
private int id;
private int donorID;
private boolean q1;
private boolean q2;
private boolean q3;
private boolean q4;
private boolean q5;
private boolean q6;
private boolean q7;
private boolean q8;
private boolean q9;
private boolean q10;
private boolean q11;
private boolean q12;
private boolean q13;
private boolean q14;
private boolean q15;
private boolean q16;
private boolean q17;
private boolean q18;
private boolean q19;
private boolean q20;

public HealthStatusCheck() {}

public HealthStatusCheck(int id, int donorID, boolean q1, boolean q2, boolean q3, boolean q4, boolean q5, boolean q6,
                         boolean q7, boolean q8, boolean q9, boolean q10, boolean q11, boolean q12, boolean q13,
                         boolean q14, boolean q15, boolean q16, boolean q17, boolean q18, boolean q19, boolean q20) {
    this.id = id;
    this.donorID = donorID;
    this.q1 = q1;
    this.q2 = q2;
    this.q3 = q3;
    this.q4 = q4;
    this.q5 = q5;
    this.q6 = q6;
    this.q7 = q7;
    this.q8 = q8;
    this.q9 = q9;
    this.q10 = q10;
    this.q11 = q11;
    this.q12 = q12;
    this.q13 = q13;
    this.q14 = q14;
    this.q15 = q15;
    this.q16 = q16;
    this.q17 = q17;
    this.q18 = q18;
    this.q19 = q19;
    this.q20 = q20;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public int getDonorID() {
    return donorID;
}

public void setDonorID(int donorID) {
    this.donorID = donorID;
}

public boolean isQ1() {
    return q1;
}

public void setQ1(boolean q1) {
    this.q1 = q1;
}

public boolean isQ2() {
    return q2;
}

public void setQ2(boolean q2) {
    this.q2 = q2;
}

public boolean isQ3() {
    return q3;
}

public void setQ3(boolean q3) {
    this.q3 = q3;
}

public boolean isQ4() {
    return q4;
}

public void setQ4(boolean q4) {
    this.q4 = q4;
}

public boolean isQ5() {
    return q5;
}

public void setQ5(boolean q5) {
    this.q5 = q5;
}

public boolean isQ6() {
    return q6;
}

public void setQ6(boolean q6) {
    this.q6 = q6;
}

public boolean isQ7() {
    return q7;
}

public void setQ7(boolean q7) {
    this.q7 = q7;
}

public boolean isQ8() {
    return q8;
}

public void setQ8(boolean q8) {
    this.q8 = q8;
}

public boolean isQ9() {
    return q9;
}

public void setQ9(boolean q9) {
    this.q9 = q9;
}

public boolean isQ10() {
    return q10;
}

public void setQ10(boolean q10) {
    this.q10 = q10;
}

public boolean isQ11() {
    return q11;
}

public void setQ11(boolean q11) {
    this.q11 = q11;
}

public boolean isQ12() {
    return q12;
}

public void setQ12(boolean q12) {
    this.q12 = q12;
}

public boolean isQ13() {
    return q13;
}

public void setQ13(boolean q13) {
    this.q13 = q13;
}

public boolean isQ14() {
    return q14;
}

public void setQ14(boolean q14) {
    this.q14 = q14;
}

public boolean isQ15() {
    return q15;
}

public void setQ15(boolean q15) {
    this.q15 = q15;
}

public boolean isQ16() {
    return q16;
}

public void setQ16(boolean q16) {
    this.q16 = q16;
}

public boolean isQ17() {
    return q17;
}

public void setQ17(boolean q17) {
    this.q17 = q17;
}

public boolean isQ18() {
    return q18;
}

public void setQ18(boolean q18) {
    this.q18 = q18;
}

public boolean isQ19() {
    return q19;
}

public void setQ19(boolean q19) {
    this.q19 = q19;
}

public boolean isQ20() {
    return q20;
}

public void setQ20(boolean q20) {
    this.q20 = q20;
}
}
</code>```

Above is my POJO class. Now I need to set the recyclerview checkboxes based on the boolean values assigned to the POJO class. In my recyclerview adapter, this POJO class is available.

Here is my adapter code:

```<code>public class DonorHealthStatusAdapter extends RecyclerView.Adapter<DonorHealthStatusAdapter.HealthViewHolder> {

private Context context;
private ArrayList<DonorHealthStatusQuestionare> questionares;
private HealthStatusCheck healthStatusCheck;

public DonorHealthStatusAdapter(Context context, ArrayList<DonorHealthStatusQuestionare> questionares,
                                HealthStatusCheck healthStatusCheck) {
    this.context = context;
    this.questionares = questionares;
    this.healthStatusCheck = healthStatusCheck;
}

@Override
public HealthViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_donor_health_info, parent, false);
    return new HealthViewHolder(view);
}

@Override
public void onBindViewHolder(final HealthViewHolder holder, int position) {

    DonorHealthStatusQuestionare questionare = questionares.get(position);
    holder.tv_questions.setText(questionare.getQuestions());

    holder.cbYes.setOnCheckedChangeListener(null);
    holder.cbNo.setOnCheckedChangeListener(null);

}

@Override
public int getItemCount() {
    return questionares.size();
}

public class HealthViewHolder extends RecyclerView.ViewHolder {

    CardView cardView;
    TextView tv_questions;
    CheckBox cbYes, cbNo;

    public HealthViewHolder(View itemView) {
        super(itemView);
        cardView = itemView.findViewById(R.id.card_view_health_status_rv);
        tv_questions = itemView.findViewById(R.id.tv_eligibility_question);
        cbYes = itemView.findViewById(R.id.checkBoxYes);
        cbNo = itemView.findViewById(R.id.checkBoxNo);
    }

}

}
</code>```

答:
So you have 20 questions which means you have 20 rows, in each row there is two check boxes (they should be either yes or no according to your class model of booleans).

in on bind view holder do this:

```<code>    @Override
  public void onBindViewHolder(final HealthViewHolder holder, int position) {

DonorHealthStatusQuestionare questionare = questionares.get(position);
holder.tv_questions.setText(questionare.getQuestions());

 //for question 1

  holder.cbYes.setChecked(questionare.isQ1());
  holder.cbNo.setChecked(questionare.isQ1());

  //for question 2

  holder.cbYes.setChecked(questionare.isQ2());
  holder.cbNo.setChecked(questionare.isQ2());

  //for question 3
  holder.cbYes.setChecked(questionare.isQ3());
  holder.cbNo.setChecked(questionare.isQ3());

  //and so on till you reach the last question (20 in your case)

     }
</code>```

Body:
I need to check my recyclerview checkboxes automatically based on boolean values coming from POJO class. below is my class details.

HealthStatusCheck.java:

public class HealthStatusCheck {
private int id;
private int donorID;
private boolean q1;
private boolean q2;
private boolean q3;
private boolean q4;
private boolean q5;
private boolean q6;
private boolean q7;
private boolean q8;
private boolean q9;
private boolean q10;
private boolean q11;
private boolean q12;
private boolean q13;
private boolean q14;
private boolean q15;
private boolean q16;
private boolean q17;
private boolean q18;
private boolean q19;
private boolean q20;

public HealthStatusCheck() {}

public HealthStatusCheck(int id, int donorID, boolean q1, boolean q2, boolean q3, boolean q4, boolean q5, boolean q6,
                         boolean q7, boolean q8, boolean q9, boolean q10, boolean q11, boolean q12, boolean q13,
                         boolean q14, boolean q15, boolean q16, boolean q17, boolean q18, boolean q19, boolean q20) {
    this.id = id;
    this.donorID = donorID;
    this.q1 = q1;
    this.q2 = q2;
    this.q3 = q3;
    this.q4 = q4;
    this.q5 = q5;
    this.q6 = q6;
    this.q7 = q7;
    this.q8 = q8;
    this.q9 = q9;
    this.q10 = q10;
    this.q11 = q11;
    this.q12 = q12;
    this.q13 = q13;
    this.q14 = q14;
    this.q15 = q15;
    this.q16 = q16;
    this.q17 = q17;
    this.q18 = q18;
    this.q19 = q19;
    this.q20 = q20;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public int getDonorID() {
    return donorID;
}

public void setDonorID(int donorID) {
    this.donorID = donorID;
}

public boolean isQ1() {
    return q1;
}

public void setQ1(boolean q1) {
    this.q1 = q1;
}

public boolean isQ2() {
    return q2;
}

public void setQ2(boolean q2) {
    this.q2 = q2;
}

public boolean isQ3() {
    return q3;
}

public void setQ3(boolean q3) {
    this.q3 = q3;
}

public boolean isQ4() {
    return q4;
}

public void setQ4(boolean q4) {
    this.q4 = q4;
}

public boolean isQ5() {
    return q5;
}

public void setQ5(boolean q5) {
    this.q5 = q5;
}

public boolean isQ6() {
    return q6;
}

public void setQ6(boolean q6) {
    this.q6 = q6;
}

public boolean isQ7() {
    return q7;
}

public void setQ7(boolean q7) {
    this.q7 = q7;
}

public boolean isQ8() {
    return q8;
}

public void setQ8(boolean q8) {
    this.q8 = q8;
}

public boolean isQ9() {
    return q9;
}

public void setQ9(boolean q9) {
    this.q9 = q9;
}

public boolean isQ10() {
    return q10;
}

public void setQ10(boolean q10) {
    this.q10 = q10;
}

public boolean isQ11() {
    return q11;
}

public void setQ11(boolean q11) {
    this.q11 = q11;
}

public boolean isQ12() {
    return q12;
}

public void setQ12(boolean q12) {
    this.q12 = q12;
}

public boolean isQ13() {
    return q13;
}

public void setQ13(boolean q13) {
    this.q13 = q13;
}

public boolean isQ14() {
    return q14;
}

public void setQ14(boolean q14) {
    this.q14 = q14;
}

public boolean isQ15() {
    return q15;
}

public void setQ15(boolean q15) {
    this.q15 = q15;
}

public boolean isQ16() {
    return q16;
}

public void setQ16(boolean q16) {
    this.q16 = q16;
}

public boolean isQ17() {
    return q17;
}

public void setQ17(boolean q17) {
    this.q17 = q17;
}

public boolean isQ18() {
    return q18;
}

public void setQ18(boolean q18) {
    this.q18 = q18;
}

public boolean isQ19() {
    return q19;
}

public void setQ19(boolean q19) {
    this.q19 = q19;
}

public boolean isQ20() {
    return q20;
}

public void setQ20(boolean q20) {
    this.q20 = q20;
}
}

Above is my POJO class. Now I need to set the recyclerview checkboxes based on the boolean values assigned to the POJO class. In my recyclerview adapter, this POJO class is available.

Here is my adapter code:

public class DonorHealthStatusAdapter extends RecyclerView.Adapter<DonorHealthStatusAdapter.HealthViewHolder> {

private Context context;
private ArrayList<DonorHealthStatusQuestionare> questionares;
private HealthStatusCheck healthStatusCheck;

public DonorHealthStatusAdapter(Context context, ArrayList<DonorHealthStatusQuestionare> questionares,
                                HealthStatusCheck healthStatusCheck) {
    this.context = context;
    this.questionares = questionares;
    this.healthStatusCheck = healthStatusCheck;
}

@Override
public HealthViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_donor_health_info, parent, false);
    return new HealthViewHolder(view);
}

@Override
public void onBindViewHolder(final HealthViewHolder holder, int position) {

    DonorHealthStatusQuestionare questionare = questionares.get(position);
    holder.tv_questions.setText(questionare.getQuestions());

    holder.cbYes.setOnCheckedChangeListener(null);
    holder.cbNo.setOnCheckedChangeListener(null);

}

@Override
public int getItemCount() {
    return questionares.size();
}

public class HealthViewHolder extends RecyclerView.ViewHolder {

    CardView cardView;
    TextView tv_questions;
    CheckBox cbYes, cbNo;

    public HealthViewHolder(View itemView) {
        super(itemView);
        cardView = itemView.findViewById(R.id.card_view_health_status_rv);
        tv_questions = itemView.findViewById(R.id.tv_eligibility_question);
        cbYes = itemView.findViewById(R.id.checkBoxYes);
        cbNo = itemView.findViewById(R.id.checkBoxNo);
    }

}

}

Body:
So you have 20 questions which means you have 20 rows, in each row there is two check boxes (they should be either yes or no according to your class model of booleans).

in on bind view holder do this:

    @Override
  public void onBindViewHolder(final HealthViewHolder holder, int position) {

DonorHealthStatusQuestionare questionare = questionares.get(position);
holder.tv_questions.setText(questionare.getQuestions());

 //for question 1

  holder.cbYes.setChecked(questionare.isQ1());
  holder.cbNo.setChecked(questionare.isQ1());

  //for question 2

  holder.cbYes.setChecked(questionare.isQ2());
  holder.cbNo.setChecked(questionare.isQ2());

  //for question 3
  holder.cbYes.setChecked(questionare.isQ3());
  holder.cbNo.setChecked(questionare.isQ3());

  //and so on till you reach the last question (20 in your case)

     }


问:
When I define functions, in what order should I put the parameters?
I often find it hard to decide and am inconsistent. Are there some rules I could follow?

For example:

```<code>def remove_except(haystack, needle, exclude_value):
    for key in hackstack:
        if key in needle and haystack[key] != exclude_value:
            hackstack.pop(key)
</code>```

could easily be:

```<code>def remove_except(needle, exclude_value, haystack):
    for key in hackstack:
        if key in needle and haystack[key] != exclude_value:
            hackstack.pop(key)
</code>```

Not a perfect example because I tend to put the variable being modified as the first parameter, e.g. haystack, and that might even be a convention but apart from that I'm unsure what to do.

I'm interested for more languages than just Python.

答: I believe that's entirely up to you.</p>

Body:
I often find it hard to decide and am inconsistent. Are there some rules I could follow?

For example:

def remove_except(haystack, needle, exclude_value):
    for key in hackstack:
        if key in needle and haystack[key] != exclude_value:
            hackstack.pop(key)

could easily be:

def remove_except(needle, exclude_value, haystack):
    for key in hackstack:
        if key in needle and haystack[key] != exclude_value:
            hackstack.pop(key)

Not a perfect example because I tend to put the variable being modified as the first parameter, e.g. haystack, and that might even be a convention but apart from that I'm unsure what to do.

I'm interested for more languages than just Python.

Body: I believe that's entirely up to you.


问:
getting the columnname and sum the values in datatable c#
```<code>for (int i = 9; i < dt.Columns.Count; i++)
{
    string dtcolumn = dt.Columns[i].ColumnName.ToString();

    dt.Rows[dt.Rows.Count - 1][i] = Convert.ToInt32(dt.Compute("SUM( " + dtcolumn + " )", "  " + dtcolumn + " > 0"));
}
</code>```

<p>it is working when column values are not null. but sometimes throwing invalidcastexception  and displaying Object cannot be cast from DBNull to other types.how to avoid invalidcastexception </p>

答:
```<code>            for (int j = 0; j < dt.Rows.Count; j++)
            {
                for (int k = 9; k < dt.Columns.Count; k++)
                {
                    if (dt.Rows[j][k].ToString() == "")
                    {
                        dt.Rows[j][k] = "0";
                    }
                }
            }

     for (int i = 9; i < dt.Columns.Count; i++)
        {
        string dtcolumn = dt.Columns[i].ColumnName.ToString();
        dt.Rows[dt.Rows.Count - 1][i] = Convert.ToInt32(dt.Compute("SUM( " + dtcolumn + " )", "1 > 0"));

         }
</code>```

thank you ,this code works without trowing any exception

Body:
for (int i = 9; i
 0"));
}

it is working when column values are not null. but sometimes throwing invalidcastexception  and displaying Object cannot be cast from DBNull to other types.how to avoid invalidcastexception

Body:
            for (int j = 0; j < dt.Rows.Count; j++)
            {
                for (int k = 9; k < dt.Columns.Count; k++)
                {
                    if (dt.Rows[j][k].ToString() == "")
                    {
                        dt.Rows[j][k] = "0";
                    }
                }
            }

     for (int i = 9; i < dt.Columns.Count; i++)
        {
        string dtcolumn = dt.Columns[i].ColumnName.ToString();
        dt.Rows[dt.Rows.Count - 1][i] = Convert.ToInt32(dt.Compute("SUM( " + dtcolumn + " )", "1 > 0"));

         }

thank you ,this code works without trowing any exception