问:
python selenium exception while fetching a url for scraping
The code runs fine before the try block. when I am fetching a url it gives exceptions .It only fetches first link and then crashes.
Please provide insights.I am getting all the links in a list but when I am fetching those urls in a for loop it crashes.</p>

```<code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import StaleElementReferenceException

baseUrl = 'http://www.thomassci.com/browse-by/suppliers'

driver = webdriver.Chrome()
driver.get(baseUrl)
mylinks= driver.find_elements_by_xpath("//*[starts-with(@id, 'ctl00') and contains(@id, 'ManufacturerName')]")

for links in mylinks:
  print links.get_attribute('href')
  datlnk=links.get_attribute('href')
  print links.text
  try:
   pghtml=driver.get(datlnk)
   wait = WebDriverWait(driver, 10)
  except:
      print('problem')

Traceback (most recent call last):
  File "D:/thomas/thomastest.py", line 17, in <module>
    print links.get_attribute('href')
  File "C:\Python27\lib\site-packages\selenium-2.46.0-py2.7.egg\selenium\webdriver\remote\webelement.py", line 102, in get_attribute
    resp = self._execute(Command.GET_ELEMENT_ATTRIBUTE, {'name': name})
  File "C:\Python27\lib\site-packages\selenium-2.46.0-py2.7.egg\selenium\webdriver\remote\webelement.py", line 404, in _execute
    return self._parent.execute(command, params)
  File "C:\Python27\lib\site-packages\selenium-2.46.0-py2.7.egg\selenium\webdriver\remote\webdriver.py", line 195, in execute
    self.error_handler.check_response(response)
  File "C:\Python27\lib\site-packages\selenium-2.46.0-py2.7.egg\selenium\webdriver\remote\errorhandler.py", line 170, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
  (Session info: chrome=61.0.3163.100)
  (Driver info: chromedriver=2.27.440174 (e97a722caafc2d3a8b807ee115bfb307f7d2cfd9),platform=Windows NT 6.1.7600 x86_64)

Process finished with exit code 1
</code>```

答:
StaleElementReferenceException means the WebElement you are trying to use is no longer valid. This happens when the DOM has changed (like moving to another url) or refreshed.

You can keep the urls in another list and iterate over it

```<code>mylinks = driver.find_elements_by_xpath("//*[starts-with(@id, 'ctl00') and contains(@id, 'ManufacturerName')]")
hrefs = []

for link in mylinks:
    hrefs.append(link.get_attribute('href'))

for href in hrefs:
    print href
    datlnk = href
    #...
</code>```

As a side note, wait = WebDriverWait(driver, 10) should be defined once, not every iteration of the loop.

Body:
The code runs fine before the try block. when I am fetching a url it gives exceptions .It only fetches first link and then crashes.
Please provide insights.I am getting all the links in a list but when I am fetching those urls in a for loop it crashes.

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import StaleElementReferenceException

baseUrl = 'http://www.thomassci.com/browse-by/suppliers'

driver = webdriver.Chrome()
driver.get(baseUrl)
mylinks= driver.find_elements_by_xpath("//*[starts-with(@id, 'ctl00') and contains(@id, 'ManufacturerName')]")

for links in mylinks:
  print links.get_attribute('href')
  datlnk=links.get_attribute('href')
  print links.text
  try:
   pghtml=driver.get(datlnk)
   wait = WebDriverWait(driver, 10)
  except:
      print('problem')

Traceback (most recent call last):
  File "D:/thomas/thomastest.py", line 17, in <module>
    print links.get_attribute('href')
  File "C:\Python27\lib\site-packages\selenium-2.46.0-py2.7.egg\selenium\webdriver\remote\webelement.py", line 102, in get_attribute
    resp = self._execute(Command.GET_ELEMENT_ATTRIBUTE, {'name': name})
  File "C:\Python27\lib\site-packages\selenium-2.46.0-py2.7.egg\selenium\webdriver\remote\webelement.py", line 404, in _execute
    return self._parent.execute(command, params)
  File "C:\Python27\lib\site-packages\selenium-2.46.0-py2.7.egg\selenium\webdriver\remote\webdriver.py", line 195, in execute
    self.error_handler.check_response(response)
  File "C:\Python27\lib\site-packages\selenium-2.46.0-py2.7.egg\selenium\webdriver\remote\errorhandler.py", line 170, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
  (Session info: chrome=61.0.3163.100)
  (Driver info: chromedriver=2.27.440174 (e97a722caafc2d3a8b807ee115bfb307f7d2cfd9),platform=Windows NT 6.1.7600 x86_64)

Process finished with exit code 1

Body:
StaleElementReferenceException means the WebElement you are trying to use is no longer valid. This happens when the DOM has changed (like moving to another url) or refreshed.

You can keep the urls in another list and iterate over it

mylinks = driver.find_elements_by_xpath("//*[starts-with(@id, 'ctl00') and contains(@id, 'ManufacturerName')]")
hrefs = []

for link in mylinks:
    hrefs.append(link.get_attribute('href'))

for href in hrefs:
    print href
    datlnk = href
    #...

As a side note, wait = WebDriverWait(driver, 10) should be defined once, not every iteration of the loop.


来源: stackexchange

问:
How Embed Unity Project in ViewController Xcode (objective c/swift)
how i can insert my unity project(2017.2.0f3) into my viewcontroller in xcode 9.0?

In this guide, actually outdated, i got the following error :

clang: error: unknown argument: '-weak-LSystem'

And in Build Phases - Compile Sources, i got only 3 files  (ViewController, main, AppDelegate), but in tutorial 90+ compiled sources

答:
Here is a most up to date guide that integrate Unity View Controller (Unity 2017.2.0f3) into Xcode 9 (and 9.1) Swift project.  If you are using Obj-C, it shares similar concept.  It also has a demo project that you can play with to see how everything works before applying to your own project.

https://github.com/jiulongw/swift-unity

ContentLicense: CC BY-SA 3.0


问:
checkbox array with corresponding input value
I fetch data from mysql in php. List all items with checkbox and quantity (rqty) as input value where user can enter quantity. But I'm not able to relate checkbox with corresponding input value (rqty) in an array. If I select first checkbox and enter quantity it works fine but if select any other checkbox and enter quantity, it's not getting updated in database. My code is as below:

```<code><?php
If (isset($_REQUEST['submit1'])!='') {
foreach($_POST['itm'] as $key=>$itm) {
$odate=date("Y-m-d H:i:s");
$rqty=$_POST['rqty'][$key];
$itm=$_POST['itm'][$key];
$sql1="insert into table (itemtype,itemname,qty ,retdate,reason) select itemtype, itemname, '$rqty', '$odate', 'Return' from stock where itemname='$itm';
mysql_query($sql1);
}
}
?>
<p>
<form action="" method="post" name="form1">
<?php
$query3 = "SELECT id, category, itemtype, itemname, qty, status FROM stock where location='godown'";
$comments3 = mysql_query($query3);
$qty = mysql_num_rows($comments3);
echo "Consumable Items: " . $qty;
print "<table class='blue'>
  <thead>
<tr>
<td width=100>Return</td>
<td width=100>Category</td>
<td width=100>Item Type</td>
<td width=100>Item Name</td>
<td width=100>Available Qty.</td>
<td width=100>Return Qty.</td>
<td width=100>Status</td>
</tr>
</thead>";

while($row1 = mysql_fetch_assoc($comments3))
{
$it=$row1['itemname'];
print "<tbody>";
print "<tr>";
print "<td><input type='checkbox' name='itm[]' value='$it'></td>";
print "<td>" . $row1['category'] . "</td>";
print "<td>" . $row1['itemtype'] . "</td>";
print "<td>" . $row1['itemname'] . "</td>";
print "<td>" . $row1['qty'] . "</td>";
print "<td><input type='text' name='rqty[]' placeholder='Enter Qty' /></td>";
print "<td>" . $row1['status'] . "</td>";
print "</tr>";
print "</tbody>";
}
print "</table>";
?>
<input type='submit' name='submit1' value='Return' />
</code>```

In inspect I can see that all rqty[] are getting posted with blank data. But in case of itm, only itm which is selected is getting posted which is correct.

enter image description here

答: Since I did not receive any solution for this, I changed the approach. Now handling each checkbox separately and not using any array. Added submit button in form list and posting required values to other php page where it's processed further.</p>

Body:
I fetch data from mysql in php. List all items with checkbox and quantity (rqty) as input value where user can enter quantity. But I'm not able to relate checkbox with corresponding input value (rqty) in an array. If I select first checkbox and enter quantity it works fine but if select any other checkbox and enter quantity, it's not getting updated in database. My code is as below:

<?php
If (isset($_REQUEST['submit1'])!='') {
foreach($_POST['itm'] as $key=>$itm) {
$odate=date("Y-m-d H:i:s");
$rqty=$_POST['rqty'][$key];
$itm=$_POST['itm'][$key];
$sql1="insert into table (itemtype,itemname,qty ,retdate,reason) select itemtype, itemname, '$rqty', '$odate', 'Return' from stock where itemname='$itm';
mysql_query($sql1);
}
}
?>

<form action="" method="post" name="form1">
<?php
$query3 = "SELECT id, category, itemtype, itemname, qty, status FROM stock where location='godown'";
$comments3 = mysql_query($query3);
$qty = mysql_num_rows($comments3);
echo "Consumable Items: " . $qty;
print "

Return
Category
Item Type
Item Name
Available Qty.
Return Qty.
Status

";

while($row1 = mysql_fetch_assoc($comments3))
{
$it=$row1['itemname'];
print "
";
print "
";
print "<input type='checkbox' name='itm[]' value='$it'>	";
print "" . $row1['category'] . "	";
print "" . $row1['itemtype'] . "	";
print "" . $row1['itemname'] . "	";
print "" . $row1['qty'] . "	";
print "<input type='text' name='rqty[]' placeholder='Enter Qty' />	";
print "" . $row1['status'] . "	";
print "
";
print "
";
}
print "
";
?>
<input type='submit' name='submit1' value='Return' />

In inspect I can see that all rqty[] are getting posted with blank data. But in case of itm, only itm which is selected is getting posted which is correct.

enter image description here


问:
how to display only one output from multiple-value result in golang
Recently, I studied that Golang can return multiple result for a function. So I write a function:

```<code>func store(x, y int) (int, int) {
    return x + y, x - y
}
</code>```

After this I write the following code:

```<code>func main() {
    a, b := store(6, 4)
    fmt.Println(a, b)
}
</code>```

And, the result is:

10 2

This is working fine.

But if I want to print only a, then how can I do this?

```<code>func main() {
    a, b := store(6, 4)
    fmt.Println(a)
}
</code>```

Result:

tmp/sandbox683412938/main.go:12:19: b declared and not used

Also, why I can't write:

```<code>func main() {
    a := store(6, 4) // ???
    fmt.Println(a)
}
</code>```

Please, guide me.

答:
You can use underscore placeholder (blank identifier) like this:

```<code>a, _ := store(6, 4)
fmt.Println(a)
</code>```

Output:

10

Here's the complete example:

```<code>package main

import (
    "fmt"
)

func store(x, y int) (int, int) {
    return x + y, x - y
}

func main() {
    a, _ := store(6, 4)
    fmt.Println(a)
}
</code>```

Live example: https://play.golang.org/p/Z366BhtRA0

Body:
Recently, I studied that Golang can return multiple result for a function. So I write a function:

func store(x, y int) (int, int) {
    return x + y, x - y
}

After this I write the following code:

func main() {
    a, b := store(6, 4)
    fmt.Println(a, b)
}

And, the result is:

10 2

This is working fine.

But if I want to print only a, then how can I do this?

func main() {
    a, b := store(6, 4)
    fmt.Println(a)
}

Result:

tmp/sandbox683412938/main.go:12:19: b declared and not used

Also, why I can't write:

func main() {
    a := store(6, 4) // ???
    fmt.Println(a)
}

Please, guide me.

Body:
You can use underscore placeholder (blank identifier) like this:

a, _ := store(6, 4)
fmt.Println(a)

Output:

10

Here's the complete example:

package main

import (
    "fmt"
)

func store(x, y int) (int, int) {
    return x + y, x - y
}

func main() {
    a, _ := store(6, 4)
    fmt.Println(a)
}

Live example: https://play.golang.org/p/Z366BhtRA0


问:
How to launch website on widget click?
I have a basic widget that displays a text field. I'm trying to figure out how to launch a website url when a user clicks on the widget itself. I can't seem to find any code on the matter.</p>

答:
Basically there are 2 options:

Link alike - create linkified TextView, so by clicking on those link you'll be there (in web)

Through onClickListener - described in previous answer.

I'd prefer 1st approach:

```<code>TextView tv=(TextView ) findViewById(R.id.myTextView);
tv.setText(Html.fromHtml("<a href='stackoverflow.com'>Go StackOverFlow!</a>"));
</code>```

ContentLicense: CC BY-SA 2.5

Title: How to launch website on widget click?

Body:
Basically there are 2 options:

Link alike - create linkified TextView, so by clicking on those link you'll be there (in web)

Through onClickListener - described in previous answer.

I'd prefer 1st approach:

TextView tv=(TextView ) findViewById(R.id.myTextView);
tv.setText(Html.fromHtml("<a href='stackoverflow.com'>Go StackOverFlow!</a>"));


问:
Jquery how to check every value on select with same ID?
I have multiple select option. I want to check if any select has specific selected value then disable a button. is possible to do that ?

here the example :

```<code><select class='test'>
<option value='open'>AA</option>
<option value='hide'>BB</option>
</select>

<select class='test'>
<option value='open'>AA</option>
<option value='hide'>BB</option>
</select>

<button id='bb'></button>
</code>```

so if there is any select with class 'test' is selected with 'hide' value, then button with id 'bb' is disabled.
Even if I select another select option with open value, if there is still one select with hide value left, the button should still disabled.
I want to do that with jQuery.

答:
So as I understand, if any of the dropdown is selected as hide then the button should get disabled. So, if you select BB option, then button gets disabled and if you select AA option, then button gets enabled.

Here is the updated code:

function checkAndDisableButton() {
  $("#bb").prop('disabled', false);
  $(".test").each(function() {
    if ($(this).val() == 'hide') {
      $("#bb").prop('disabled', true);
    }
  });
}

$("select").on('change', checkAndDisableButton);```
<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>
<select class='test'>
<option value='open'>AA</option>
<option value='hide'>BB</option>
</select>

<select class='test'>
<option value='open'>AA</option>
<option value='hide'>BB</option>
</select>

<button id='bb'>Button</button></code>```

Body:
I have multiple select option. I want to check if any select has specific selected value then disable a button. is possible to do that ?

here the example :

<select class='test'>
<option value='open'>AA</option>
<option value='hide'>BB</option>
</select>

<select class='test'>
<option value='open'>AA</option>
<option value='hide'>BB</option>
</select>

<button id='bb'></button>

so if there is any select with class 'test' is selected with 'hide' value, then button with id 'bb' is disabled.
Even if I select another select option with open value, if there is still one select with hide value left, the button should still disabled.
I want to do that with jQuery.

Body:
So as I understand, if any of the dropdown is selected as hide then the button should get disabled. So, if you select BB option, then button gets disabled and if you select AA option, then button gets enabled.

Here is the updated code:

function checkAndDisableButton() {
  $("#bb").prop('disabled', false);
  $(".test").each(function() {
    if ($(this).val() == 'hide') {
      $("#bb").prop('disabled', true);
    }
  });
}

$("select").on('change', checkAndDisableButton);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class='test'>
<option value='open'>AA</option>
<option value='hide'>BB</option>
</select>

<select class='test'>
<option value='open'>AA</option>
<option value='hide'>BB</option>
</select>

<button id='bb'>Button</button>


问:
mvn: command not found
I'm trying to run a pipeline with jenkinsfile on a specific for which I don't have access to manage the path. But I'm having this error can any one know how to solve this one?

答:
You need to install Maven on the build agent executing the job. An alternative by Jenkins is that it can install Maven for you. This can be configured in the Global Tool Configuration of the Jenkins Master.

If you are really only allowed to modify the Jenkinsfile, you could first download and unpack maven into some local directory and then call it from there.

Title: mvn: command not found


答:
You can do it like this, it will check if any select has an selected option with the value of hide. If so, it will disable the button.

```<code>$(".test").change(function() {
  var flag = true;
  $('.test').each(function() {
    if ($(this).val() == "hide") {
      flag = false;
    }
  });
  if (flag) {
    $("#bb").prop("disabled", false)
  } else {
    $("#bb").prop("disabled", true)
  }
})
</code>```

Working demo

$(".test").change(function() {
  var flag = true;
  $('.test').each(function() {
    if ($(this).val() == "hide") {
      flag = false;
    }
  });
  if (flag) {
    $("#bb").prop("disabled", false)
  } else {
    $("#bb").prop("disabled", true)
  }
})```
<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>
<select class='test'>
<option value='open'>AA</option>
<option value='hide'>BB</option>
</select>

<select class='test'>
<option value='open'>AA</option>
<option value='hide'>BB</option>
</select>

<button id='bb'>test me</button></code>```

Title: Jquery how to check every value on select with same ID?

Body:
You can do it like this, it will check if any select has an selected option with the value of hide. If so, it will disable the button.

$(".test").change(function() {
  var flag = true;
  $('.test').each(function() {
    if ($(this).val() == "hide") {
      flag = false;
    }
  });
  if (flag) {
    $("#bb").prop("disabled", false)
  } else {
    $("#bb").prop("disabled", true)
  }
})

Working demo

$(".test").change(function() {
  var flag = true;
  $('.test').each(function() {
    if ($(this).val() == "hide") {
      flag = false;
    }
  });
  if (flag) {
    $("#bb").prop("disabled", false)
  } else {
    $("#bb").prop("disabled", true)
  }
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class='test'>
<option value='open'>AA</option>
<option value='hide'>BB</option>
</select>

<select class='test'>
<option value='open'>AA</option>
<option value='hide'>BB</option>
</select>

<button id='bb'>test me</button>


问:
How to pick every 10 lines from a txt file using python?
I need to write a code where I have huge 7000+ lines of text file. I need to split every 10lines and write it to another file.  </p>

答:
```<code>with open(fname) as f:
    content = f.readlines()
    with open(fname) as g:
        len_f = len(content)
        for x in xrange(0, len_f):
            if x % 10 = 0:
                g.write(content[x])
                g.write("\n") #For new-line
            else:
                pass
        g.close()
    f.close()
</code>```

Should work! (Python 2.x)

Key take-aways:

1) Don't open / close the write-file after writing each line.

2) Close the files upon completion.

Body:
with open(fname) as f:
    content = f.readlines()
    with open(fname) as g:
        len_f = len(content)
        for x in xrange(0, len_f):
            if x % 10 = 0:
                g.write(content[x])
                g.write("\n") #For new-line
            else:
                pass
        g.close()
    f.close()

Should work! (Python 2.x)

Key take-aways:

1) Don't open / close the write-file after writing each line.

2) Close the files upon completion.


问:
Codeigniter PHP submit post
i have a simple form using codeigniter and there is a submit button:

```<code><?php echo form_open('myController/add'); ?>
<input type="text" class="form-control" name="myInput" value='abc'>
<button type="submit" name="Submit">Save</button>
<?php echo form_close(); ?>
</code>```

but it doesn't contain Submit when i run this code:

```<code>function add(){
  print_r($_POST);
}
</code>```

here is the result:

```<code>Array ( [myInput] => abc )
</code>```

i think the result should be like this:

```<code>Array ( [myInput] => abc [Submit] =>)
</code>```

please help.. thank you.

答:
Per Mozilla's documentation for the button element, you can have a value attribute. See here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button

This means you could just do this:

```<code><button type="submit" name="Submit" value="something">Save</button>
</code>```

and then you would have:

```<code>$_POST['Submit'] = "something";
</code>```

BUT in your question it looks like you want the Submit key to be present, even if there is no value, and I don't think that's going to work. I do believe you will have to have something as a value in order for the key to be present.

Title: Codeigniter PHP submit post

Body:
i have a simple form using codeigniter and there is a submit button:

<?php echo form_open('myController/add'); ?>
<input type="text" class="form-control" name="myInput" value='abc'>
<button type="submit" name="Submit">Save</button>
<?php echo form_close(); ?>

but it doesn't contain Submit when i run this code:

function add(){
  print_r($_POST);
}

here is the result:

Array ( [myInput] => abc )

i think the result should be like this:

Array ( [myInput] => abc [Submit] =>)

please help.. thank you.

Body:
Per Mozilla's documentation for the button element, you can have a value attribute. See here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button

This means you could just do this:

<button type="submit" name="Submit" value="something">Save</button>

and then you would have:

$_POST['Submit'] = "something";

BUT in your question it looks like you want the Submit key to be present, even if there is no value, and I don't think that's going to work. I do believe you will have to have something as a value in order for the key to be present.


问:
Syntax error When convert from MySQL to T-SQL
I'm new in SQL .
I'm converting mysql to SQL.

I've found an error when I use DateAdd function.

Here is the query:

```<code>SELECT
      [id],
      [test_code],
      [test_name],
      [test_price],
      [discount],
      DATEADD(CURRENT_TIMESTAMP, INTERVAL [test_duration] HOUR) as delivery_date,
      [is_active]
    FROM [icddrb_tblab].[dbo].[tb_test]
    WHERE [icddrb_tblab].[dbo].[tb_test].[id] =0
</code>```

It gives error:
Msg 102, Level 15, State 1, Line 7

Incorrect syntax near 'test_duration'.'

Can anyone suggest me, where is the issue.

答:
Solved:

```<code>DATEADD(HOUR,[test_duration], CURRENT_TIMESTAMP) as delivery_date,
</code>```

its the actual format.

Body:
I'm new in SQL .
I'm converting mysql to SQL.

I've found an error when I use DateAdd function.

Here is the query:

SELECT
      [id],
      [test_code],
      [test_name],
      [test_price],
      [discount],
      DATEADD(CURRENT_TIMESTAMP, INTERVAL [test_duration] HOUR) as delivery_date,
      [is_active]
    FROM [icddrb_tblab].[dbo].[tb_test]
    WHERE [icddrb_tblab].[dbo].[tb_test].[id] =0

It gives error:
Msg 102, Level 15, State 1, Line 7

Incorrect syntax near 'test_duration'.'

Can anyone suggest me, where is the issue.

Body:
Solved:

DATEADD(HOUR,[test_duration], CURRENT_TIMESTAMP) as delivery_date,

its the actual format.


问:
Plone: TinyMCE upload files
I'm trying to find a solution for files uploading directly with TinyMCE. Imagine creating a list of pdf files by uploading them using a custom button.

Is there something already done I can use? collective.clipboardupload seems to be a solution only for images.

答:
MoxieManager may be what you're looking for. It's a premium plugin made by the same developers as TinyMCE itself. </p>

<p>https://www.tinymce.com/docs/enterprise/manage-files-and-images/ </p>

Title: Plone: TinyMCE upload files

Body:
MoxieManager may be what you're looking for. It's a premium plugin made by the same developers as TinyMCE itself.

https://www.tinymce.com/docs/enterprise/manage-files-and-images/


问:
display recyclerview checkbox as selected and un-selected based on boolean values android
Let me tell you what exactly I needed. I need to load 20 questions from my MySql DB to recyclerview. Questions are saved in a table that has two columns ie, id and question. I can successfully load these questions to my recyclerview with the help of an adapter. Here is the twist, I need to mark these questions as "Yes" or "No" in my recyclerview by using checkboxes for each based on what exactly logged in user answered before this questions from his profile. Also, I expect good database and object class design solution in order to achieve this.

Here what I have tried,

Adapter Class:

```<code>public class MyHealthInfoAdapter extends RecyclerView.Adapter<MyHealthInfoAdapter.MyHealthViewHolder> {

private Context context;
private ArrayList<DonorHealthStatusQuestionare> listQuestions;

public MyHealthInfoAdapter(Context context, ArrayList<DonorHealthStatusQuestionare> listQuestions) {
    this.context = context;
    this.listQuestions = listQuestions;
}

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

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

    DonorHealthStatusQuestionare donorHealthStatusQuestionare = listQuestions.get(position);
    holder.tvQuestion.setText(donorHealthStatusQuestionare.getQuestions());

}

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

public class MyHealthViewHolder extends RecyclerView.ViewHolder{

    CardView cvParent;
    TextView tvQuestion;
    CheckBox cbYes, cbNo;

    public MyHealthViewHolder(View itemView) {
        super(itemView);
        cvParent = itemView.findViewById(R.id.card_view_my_health_status_rv);
        tvQuestion = itemView.findViewById(R.id.tv_eligibility_question_my_info);
        cbYes = itemView.findViewById(R.id.checkBoxYes_my_health_info);
        cbNo = itemView.findViewById(R.id.checkBoxNo_my_health_info);

    }
}
}
</code>```

Fragment:

```<code>public class DonorHealthStatus extends Fragment {

private static final int MY_SOCKET_TIMEOUT_MS = 100000;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private DonorHealthStatusAdapter donorHealthStatusAdapter;
private ArrayList<DonorHealthStatusQuestionare> donorHealthStatusQuestionares = new ArrayList<>();
private HealthStatusCheck statusCheck = new HealthStatusCheck();
private String donorID;
private Donor donor;
private boolean checked;

public DonorHealthStatus() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_donor_health_status, container, false);
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    donor = ((DisplayDonorDetails)getActivity()).getDonor();
    donorID = donor.getUserID();

    getHealthStatus(new HealthStatusCallBack() {
        @Override
        public void onSuccess(HealthStatusCheck healthStatusCheck) {
            statusCheck = healthStatusCheck;
            setHealthStatusView();
        }

        @Override
        public void onFail(String msg) {}
    });

}

// SETTING HEALTH STATUS POJO CLASS FROM DATABASE.
private void getHealthStatus(final HealthStatusCallBack healthStatusCallBack) {
    Utility.checkNetworkConnectionBoolean(getActivity());

    if(Utility.isNetworkEnabled){
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.GET_HEALTH_STATUS,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        try {

                            JSONArray jsonArray = new JSONArray(response);
                            JSONObject jsonObject = jsonArray.getJSONObject(0);
                            String code = jsonObject.getString("code");

                            if(code.equals("0001")){

                                statusCheck.setId(Integer.valueOf(jsonObject.getString("id")));
                                statusCheck.setDonorID(Integer.valueOf(jsonObject.getString("donorID")));

                                if(jsonObject.getString("q1").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q1").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q2").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q2").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q3").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q3").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q4").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q4").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q5").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q5").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q6").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q6").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q7").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q7").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q8").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q8").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q9").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q9").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q10").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q10").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q11").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q11").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q12").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q12").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q13").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q13").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q14").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q14").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q15").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q15").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q16").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q16").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q17").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q17").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q18").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q18").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q19").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q19").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q20").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q20").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }

                            }

                            healthStatusCallBack.onSuccess(statusCheck);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {}
                }
        ){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("donorID", donorID);
                return params;
            }
        };

        stringRequest.setRetryPolicy(new DefaultRetryPolicy(MY_SOCKET_TIMEOUT_MS, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        NetworkRequestSingleTon.getOurInstance(getActivity()).addToRequestQue(stringRequest);
    }else {
        Utility.checkNetworkConnectionAlert(getActivity());
    }

}

// SETTING RECYCLER VIEW OF QUESTIONARE FROM DATABASE.
private void setHealthStatusView() {

    recyclerView = getActivity().findViewById(R.id.rv_donor_health_info);
    layoutManager = new LinearLayoutManager(getActivity());

    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setItemAnimator(new DefaultItemAnimator());

    donorHealthStatusAdapter = new DonorHealthStatusAdapter(getActivity(),
            donorHealthStatusQuestionares, statusCheck);

    recyclerView.setAdapter(donorHealthStatusAdapter);

    Utility.checkGpsConnectionBoolean(getActivity());
    if(Utility.isNetworkEnabled){

        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.GET_HEALTH_QUESTIONARE,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        try {

                            JSONArray jsonArray = new JSONArray(response);

                            int count = 0;

                            while (count < jsonArray.length()){
                                JSONObject jsonObject = jsonArray.getJSONObject(count);

                                DonorHealthStatusQuestionare donorHealthStatusQuestionare =
                                        new DonorHealthStatusQuestionare();

                                donorHealthStatusQuestionare.setId(Integer.valueOf(jsonObject.getString("id")));
                                donorHealthStatusQuestionare.setQuestions(jsonObject.getString("questions"));

                                donorHealthStatusQuestionares.add(donorHealthStatusQuestionare);
                                count ++;

                            }

                            donorHealthStatusAdapter.notifyDataSetChanged();

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                }
        );
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(MY_SOCKET_TIMEOUT_MS, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        NetworkRequestSingleTon.getOurInstance(getActivity()).addToRequestQue(stringRequest);

    }else {
        Utility.checkNetworkConnectionAlert(getActivity());
    }

}

// CALL BACK INTERFACE TO GET POJO CLASS FROM VOLLEY BACKGROUND ACTIVITY.
public interface HealthStatusCallBack{

    void onSuccess(HealthStatusCheck healthStatusCheck);

    void onFail(String msg);
}
}
</code>```

LAYOUT XML:

```<code><android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/card_view_health_status_rv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="1dp">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:baselineAligned="false"
    android:orientation="horizontal"
    android:padding="12dp">

    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:layout_weight="1">

        <TextView
            android:id="@+id/tv_eligibility_question"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/health_status_radio_group"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0">

        <CheckBox
            android:id="@+id/checkBoxYes"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="16dp"
            android:layout_marginRight="16dp"
            android:text="@string/yes" />

        <CheckBox
            android:layout_toRightOf="@+id/checkBoxYes"
            android:layout_toEndOf="@+id/checkBoxYes"
            android:id="@+id/checkBoxNo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/no" />

    </RelativeLayout>

</LinearLayout>
</code>```

Result Check POJO Class:

```<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>```

Questions POJO class:

```<code>public class DonorHealthStatusQuestionare {
private int id;
private String questions;
boolean isSelected;

public DonorHealthStatusQuestionare() {}

public DonorHealthStatusQuestionare(int id, String questions) {
    this.id = id;
    this.questions = questions;
}

public int getId() {
    return id;
}

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

public String getQuestions() {
    return questions;
}

public void setQuestions(String questions) {
    this.questions = questions;
}

public boolean isSelected() {
    return isSelected;
}

public void setSelected(boolean selected) {
    isSelected = selected;
}
}
</code>```

答:
Checkbox is enable false in Adapter XMl file as code below

```<code> <CheckBox
        android:id="@+id/cb"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:enabled="false"/>
</code>```

Then Set recycleriew adapter as below in activity

```<code>TestAdapter testAdpter = new TestAdapter(this, testList);
recyclerview.setAdapter(testAdpter);
</code>```

Then set your Adapter like below

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

private final Activity mContext;
private final List<TestData> mList;
private final LayoutInflater inflater;

public TestAdapter(Activity activity, List<TestData> testList) {
    this.mContext = activity;
    this.mList = testList;
    this.inflater = LayoutInflater.from(mContext);
}

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

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

    if (mList.get(position).isSelected()) {
        holder.cb.setChecked(true);
    } else {
        holder.cb.setChecked(false);
    }

  }

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

public class ViewHolder extends RecyclerView.ViewHolder {
    private final CheckBox cb;

    public ViewHolder(View view) {
        super(view);
         cb = (CheckBox) view.findViewById(R.id.cb);
    }
}
}
</code>```

Body:
Let me tell you what exactly I needed. I need to load 20 questions from my MySql DB to recyclerview. Questions are saved in a table that has two columns ie, id and question. I can successfully load these questions to my recyclerview with the help of an adapter. Here is the twist, I need to mark these questions as "Yes" or "No" in my recyclerview by using checkboxes for each based on what exactly logged in user answered before this questions from his profile. Also, I expect good database and object class design solution in order to achieve this.

Here what I have tried,

Adapter Class:

public class MyHealthInfoAdapter extends RecyclerView.Adapter<MyHealthInfoAdapter.MyHealthViewHolder> {

private Context context;
private ArrayList<DonorHealthStatusQuestionare> listQuestions;

public MyHealthInfoAdapter(Context context, ArrayList<DonorHealthStatusQuestionare> listQuestions) {
    this.context = context;
    this.listQuestions = listQuestions;
}

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

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

    DonorHealthStatusQuestionare donorHealthStatusQuestionare = listQuestions.get(position);
    holder.tvQuestion.setText(donorHealthStatusQuestionare.getQuestions());

}

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

public class MyHealthViewHolder extends RecyclerView.ViewHolder{

    CardView cvParent;
    TextView tvQuestion;
    CheckBox cbYes, cbNo;

    public MyHealthViewHolder(View itemView) {
        super(itemView);
        cvParent = itemView.findViewById(R.id.card_view_my_health_status_rv);
        tvQuestion = itemView.findViewById(R.id.tv_eligibility_question_my_info);
        cbYes = itemView.findViewById(R.id.checkBoxYes_my_health_info);
        cbNo = itemView.findViewById(R.id.checkBoxNo_my_health_info);

    }
}
}

Fragment:

public class DonorHealthStatus extends Fragment {

private static final int MY_SOCKET_TIMEOUT_MS = 100000;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private DonorHealthStatusAdapter donorHealthStatusAdapter;
private ArrayList<DonorHealthStatusQuestionare> donorHealthStatusQuestionares = new ArrayList<>();
private HealthStatusCheck statusCheck = new HealthStatusCheck();
private String donorID;
private Donor donor;
private boolean checked;

public DonorHealthStatus() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_donor_health_status, container, false);
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    donor = ((DisplayDonorDetails)getActivity()).getDonor();
    donorID = donor.getUserID();

    getHealthStatus(new HealthStatusCallBack() {
        @Override
        public void onSuccess(HealthStatusCheck healthStatusCheck) {
            statusCheck = healthStatusCheck;
            setHealthStatusView();
        }

        @Override
        public void onFail(String msg) {}
    });

}

// SETTING HEALTH STATUS POJO CLASS FROM DATABASE.
private void getHealthStatus(final HealthStatusCallBack healthStatusCallBack) {
    Utility.checkNetworkConnectionBoolean(getActivity());

    if(Utility.isNetworkEnabled){
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.GET_HEALTH_STATUS,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        try {

                            JSONArray jsonArray = new JSONArray(response);
                            JSONObject jsonObject = jsonArray.getJSONObject(0);
                            String code = jsonObject.getString("code");

                            if(code.equals("0001")){

                                statusCheck.setId(Integer.valueOf(jsonObject.getString("id")));
                                statusCheck.setDonorID(Integer.valueOf(jsonObject.getString("donorID")));

                                if(jsonObject.getString("q1").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q1").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q2").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q2").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q3").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q3").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q4").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q4").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q5").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q5").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q6").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q6").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q7").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q7").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q8").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q8").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q9").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q9").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q10").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q10").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q11").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q11").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q12").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q12").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q13").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q13").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q14").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q14").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q15").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q15").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q16").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q16").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q17").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q17").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q18").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q18").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q19").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q19").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q20").equals("0")){
                                    checked = false;
                                    statusCheck.setQ1(checked);
                                }else if(jsonObject.getString("q20").equals("1")){
                                    checked = true;
                                    statusCheck.setQ1(checked);
                                }

                            }

                            healthStatusCallBack.onSuccess(statusCheck);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {}
                }
        ){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("donorID", donorID);
                return params;
            }
        };

        stringRequest.setRetryPolicy(new DefaultRetryPolicy(MY_SOCKET_TIMEOUT_MS, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        NetworkRequestSingleTon.getOurInstance(getActivity()).addToRequestQue(stringRequest);
    }else {
        Utility.checkNetworkConnectionAlert(getActivity());
    }

}

// SETTING RECYCLER VIEW OF QUESTIONARE FROM DATABASE.
private void setHealthStatusView() {

    recyclerView = getActivity().findViewById(R.id.rv_donor_health_info);
    layoutManager = new LinearLayoutManager(getActivity());

    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setItemAnimator(new DefaultItemAnimator());

    donorHealthStatusAdapter = new DonorHealthStatusAdapter(getActivity(),
            donorHealthStatusQuestionares, statusCheck);

    recyclerView.setAdapter(donorHealthStatusAdapter);

    Utility.checkGpsConnectionBoolean(getActivity());
    if(Utility.isNetworkEnabled){

        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.GET_HEALTH_QUESTIONARE,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        try {

                            JSONArray jsonArray = new JSONArray(response);

                            int count = 0;

                            while (count < jsonArray.length()){
                                JSONObject jsonObject = jsonArray.getJSONObject(count);

                                DonorHealthStatusQuestionare donorHealthStatusQuestionare =
                                        new DonorHealthStatusQuestionare();

                                donorHealthStatusQuestionare.setId(Integer.valueOf(jsonObject.getString("id")));
                                donorHealthStatusQuestionare.setQuestions(jsonObject.getString("questions"));

                                donorHealthStatusQuestionares.add(donorHealthStatusQuestionare);
                                count ++;

                            }

                            donorHealthStatusAdapter.notifyDataSetChanged();

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                }
        );
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(MY_SOCKET_TIMEOUT_MS, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        NetworkRequestSingleTon.getOurInstance(getActivity()).addToRequestQue(stringRequest);

    }else {
        Utility.checkNetworkConnectionAlert(getActivity());
    }

}

// CALL BACK INTERFACE TO GET POJO CLASS FROM VOLLEY BACKGROUND ACTIVITY.
public interface HealthStatusCallBack{

    void onSuccess(HealthStatusCheck healthStatusCheck);

    void onFail(String msg);
}
}

LAYOUT XML:

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/card_view_health_status_rv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="1dp">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:baselineAligned="false"
    android:orientation="horizontal"
    android:padding="12dp">

    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:layout_weight="1">

        <TextView
            android:id="@+id/tv_eligibility_question"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/health_status_radio_group"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0">

        <CheckBox
            android:id="@+id/checkBoxYes"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="16dp"
            android:layout_marginRight="16dp"
            android:text="@string/yes" />

        <CheckBox
            android:layout_toRightOf="@+id/checkBoxYes"
            android:layout_toEndOf="@+id/checkBoxYes"
            android:id="@+id/checkBoxNo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/no" />

    </RelativeLayout>

</LinearLayout>

Result Check POJO Class:

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;
}
}

Questions POJO class:

public class DonorHealthStatusQuestionare {
private int id;
private String questions;
boolean isSelected;

public DonorHealthStatusQuestionare() {}

public DonorHealthStatusQuestionare(int id, String questions) {
    this.id = id;
    this.questions = questions;
}

public int getId() {
    return id;
}

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

public String getQuestions() {
    return questions;
}

public void setQuestions(String questions) {
    this.questions = questions;
}

public boolean isSelected() {
    return isSelected;
}

public void setSelected(boolean selected) {
    isSelected = selected;
}
}

Body:
Checkbox is enable false in Adapter XMl file as code below

 <CheckBox
        android:id="@+id/cb"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:enabled="false"/>

Then Set recycleriew adapter as below in activity

TestAdapter testAdpter = new TestAdapter(this, testList);
recyclerview.setAdapter(testAdpter);

Then set your Adapter like below

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

private final Activity mContext;
private final List<TestData> mList;
private final LayoutInflater inflater;

public TestAdapter(Activity activity, List<TestData> testList) {
    this.mContext = activity;
    this.mList = testList;
    this.inflater = LayoutInflater.from(mContext);
}

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

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

    if (mList.get(position).isSelected()) {
        holder.cb.setChecked(true);
    } else {
        holder.cb.setChecked(false);
    }

  }

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

public class ViewHolder extends RecyclerView.ViewHolder {
    private final CheckBox cb;

    public ViewHolder(View view) {
        super(view);
         cb = (CheckBox) view.findViewById(R.id.cb);
    }
}
}


问:
OnSharedPreferenceChangeListener implemented between apps with sharedUserID?
I have App A and App B under sharedUserId. In App B, I would like to get the sharedPreferences of A, when they change. Right now I can get app A's sharedPreferences, but only on recompile. Is this possible?

This is an example of what I'm attempting in app B:

```<code>// get Context of Shared App
     sharedContext = this.createPackageContext("com.app.A",Context.CONTEXT_IGNORE_SECURITY);
// get desired preferences from app A
     myPrefs = sharedContext.getSharedPreferences(PREFERENCES,Context.MODE_PRIVATE);
// keeping local copy of this listener
     listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
     public void onSharedPreferenceChanged(SharedPreferences myPrefs, String key) {
          if (key.equals(PREFERENCES)) {
                       // Do something
               Log.d("Test", "preferences were updated");
               }
          }
     };
// register listener
myPrefs.registerOnSharedPreferenceChangeListener(listener);
</code>```

答:
set android:process in the manifest of each app.

Also key.equals(PREFERENCES) should be the name of the specific preference to grab, key.equals("key:example") rather than the name of the shared Preference.

Body:
I have App A and App B under sharedUserId. In App B, I would like to get the sharedPreferences of A, when they change. Right now I can get app A's sharedPreferences, but only on recompile. Is this possible?

This is an example of what I'm attempting in app B:

// get Context of Shared App
     sharedContext = this.createPackageContext("com.app.A",Context.CONTEXT_IGNORE_SECURITY);
// get desired preferences from app A
     myPrefs = sharedContext.getSharedPreferences(PREFERENCES,Context.MODE_PRIVATE);
// keeping local copy of this listener
     listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
     public void onSharedPreferenceChanged(SharedPreferences myPrefs, String key) {
          if (key.equals(PREFERENCES)) {
                       // Do something
               Log.d("Test", "preferences were updated");
               }
          }
     };
// register listener
myPrefs.registerOnSharedPreferenceChangeListener(listener);


问:
Can I use ABAP Unit tests in classic ABAP report?
I would like to implement ABAP Unit tests in my ABAP programs, but my first report is a classic ABAP report, no OO classes at all.

Is this even possible? Or ABAP Unit intended solely on OO classes?

Can I use it with subroutines?

```<code>PERFORM get_date_range using sy-date changing lv_fromdate lv_todate.
</code>```

P.S. I'm a long time Java developer still learning ABAP.

答:
In ABAP programming it will allow the developer to do the unit testing.

ABAP also contains MACRO's concept as like in C-programming, but in ABAP MACROS does not allows unit testing.

```<code>REPORT ZDEMO_INTERNALTABLES.

TYPES : BEGIN OF ty_scarr,

        carrid TYPE scarr-carrid,
        carrname TYPE scarr-carrname,
        END OF ty_scarr.

DATA : it_scarr TYPE STANDARD TABLE OF ty_scarr,

       wa_scarr TYPE ty_scarr.
      PERFORM SA .

*&---------------------------------------------------------------------*
*&      Form  SA
*&---------------------------------------------------------------------*
*       text
*----------------------------------------------------------------------*
*  -->  p1        text
*  <--  p2        text
*----------------------------------------------------------------------*

FORM SA .

  wa_scarr-carrid = 'AA'.
        wa_scarr-carrname = 'American airlines'.
        insert wa_scarr into table it_scarr .

         wa_scarr-carrid = 'df'.
        wa_scarr-carrname = 'xmy demy airlines'.
        insert wa_scarr into table it_scarr.

         wa_scarr-carrid = 'AC'.
        wa_scarr-carrname = 'AIRLINES'.
        APPEND WA_SCARR TO IT_SCARR.

         wa_scarr-carrid = 'AD'.
        wa_scarr-carrname = 'American airlines'.
        insert wa_scarr into table it_scarr.

        if SY-SUBRC = 0.
          ENDIF.
ENDFORM.                    " SA
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I would like to implement ABAP Unit tests in my ABAP programs, but my first report is a classic ABAP report, no OO classes at all.

Is this even possible? Or ABAP Unit intended solely on OO classes?

Can I use it with subroutines?

PERFORM get_date_range using sy-date changing lv_fromdate lv_todate.

P.S. I'm a long time Java developer still learning ABAP.

Body:
In ABAP programming it will allow the developer to do the unit testing.

ABAP also contains MACRO's concept as like in C-programming, but in ABAP MACROS does not allows unit testing.

REPORT ZDEMO_INTERNALTABLES.

TYPES : BEGIN OF ty_scarr,

        carrid TYPE scarr-carrid,
        carrname TYPE scarr-carrname,
        END OF ty_scarr.

DATA : it_scarr TYPE STANDARD TABLE OF ty_scarr,

       wa_scarr TYPE ty_scarr.
      PERFORM SA .

*&---------------------------------------------------------------------*
*&      Form  SA
*&---------------------------------------------------------------------*
*       text
*----------------------------------------------------------------------*
*  -->  p1        text
*  <--  p2        text
*----------------------------------------------------------------------*

FORM SA .

  wa_scarr-carrid = 'AA'.
        wa_scarr-carrname = 'American airlines'.
        insert wa_scarr into table it_scarr .

         wa_scarr-carrid = 'df'.
        wa_scarr-carrname = 'xmy demy airlines'.
        insert wa_scarr into table it_scarr.

         wa_scarr-carrid = 'AC'.
        wa_scarr-carrname = 'AIRLINES'.
        APPEND WA_SCARR TO IT_SCARR.

         wa_scarr-carrid = 'AD'.
        wa_scarr-carrname = 'American airlines'.
        insert wa_scarr into table it_scarr.

        if SY-SUBRC = 0.
          ENDIF.
ENDFORM.                    " SA


问:
Limit amount of links shown with Laravel pagination
Any easy way to limit how many links are shown with Laravels pagination?

Currently it shows 13 links at most (Prev, 1 2 3 4 5 7 8 .. 78 79 next)

This however is too much for mobile devices and becomes a two line navigation... is there any way to set the links to e.g. only show 10?

I have messed around with the pagination presenter but nothing actually seemed to work.

Thanks

答:
My table was too narrow so, I decided to show only first and the last li (The Next and Back arrows) of pagination with jQuery filter(). You can customize this further.

```<code>$('ul.pagination li').hide().filter(':lt(1), :nth-last-child(1)').show();
</code>```

Make sure to add it before the end of body tag.

Body:
My table was too narrow so, I decided to show only first and the last li (The Next and Back arrows) of pagination with jQuery filter(). You can customize this further.

$('ul.pagination li').hide().filter(':lt(1), :nth-last-child(1)').show();

Make sure to add it before the end of body tag.


问:
How do I perform an animation every-time a post is liked in my feed in swift 3?
I have an Instagram Like feed
Feed has many posts. Each post has like button.

Everytime user taps on like
MyUiView

```<code>let likeImageView: UIButton = {
            let button = UIButton(type: .custom)
            button.setImage(#imageLiteral(resourceName: "like_unselected"), for: .normal)
            let tap = UITapGestureRecognizer(target: self, action: #selector(loveButtonTapped))
            tap.numberOfTapsRequired = 1
            button.addGestureRecognizer(tap)

            return button
        }()
</code>```

I am getting and passing the location of user tap through delegate.I get correct needed location using this method.

```<code>@objc func loveButtonTapped(sender: UITapGestureRecognizer){
        guard var location : CGPoint = sender.view?.superview?.frame.origin else { return }
        var loc = convert(location, to: nil)
        self.delegate?.onloveButtonTapped(loc: loc, for: self)
    }
</code>```

Now on my FeedController (which is UIcollectionViewController)

```<code>func likeButtonTapped(loc: CGPoint, for cell: PostUi){
            print("like button tapped")
            var touchLocation: CGPoint = loc
            print(touchLocation)
        ...
        ... //like implementation and checks
        ...

 var i = Int(location.x)
 var j = Int(location.y)

let path = UIBezierPath()

 path.move(to: CGPoint(x:i, y:j))
 //more code for animation
</code>```

}

Now, when I tap on like button from the first post I the animation works but when I scroll down to another post and tap on like button, animation still works but can't be seen because it's happening on the top side. I get changed Coordinates for every like button but the path CGPoint starting is counted from the feed starting point. What should I do make it work correctly?

答:
First thing is I don't get why do you pass the location to FeedController while you can do all the animation in UICollectionViewCell's Class. Is the animation happens with any other UIViews that is not inside the Post Cell (UICollectionViewCell)?</p>

```<code>@IBAction func likeBtnTapped(_ sender: UIButton) {
    if post != nil {
        putLike(postId: post!.id, userId: user.id, isLiked: post!.liked)
    }
}

// Network Requests
func putLike(postId: Int, userId: Int, isLiked: Bool) {
    let httpService = HTTPService()
    httpService.putLikeRequest(postId: postId, userId: userId, isLiked: isLiked, onSuccess: { (liked, likeText) in
        self.post?.liked            = liked
        self.post?.likesText        = likeText
        if self.post != nil {
            self.likeCountLbl.text  = self.post!.likesText
            self.delegate?.replaceLikedPostInArray(post: self.post!)
            self.likeButtonScaleAnimation(liked: liked)
        }
    }) { (error) in
        print("putLikeRequest error : \(error)")
    }
}

func likeButtonScaleAnimation(liked: Bool) {
    UIView.animate(withDuration: 0.4,
                   animations: {
                    self.likeBtn.transform      = liked ? CGAffineTransform(scaleX: 1.4, y: 1.4)    : CGAffineTransform(scaleX: 0.6, y: 0.6)
                    self.likeBtn.tintColor      = liked ? UIColor.blue                              : UIColor.darkGray
                   },
                   completion: { _ in
                    UIView.animate(withDuration: 0.4) {
                        self.likeBtn.transform  = CGAffineTransform.identity
                        }
                  })
}
</code>```

Body:
I have an Instagram Like feed
Feed has many posts. Each post has like button.

Everytime user taps on like
MyUiView

let likeImageView: UIButton = {
            let button = UIButton(type: .custom)
            button.setImage(#imageLiteral(resourceName: "like_unselected"), for: .normal)
            let tap = UITapGestureRecognizer(target: self, action: #selector(loveButtonTapped))
            tap.numberOfTapsRequired = 1
            button.addGestureRecognizer(tap)

            return button
        }()

I am getting and passing the location of user tap through delegate.I get correct needed location using this method.

@objc func loveButtonTapped(sender: UITapGestureRecognizer){
        guard var location : CGPoint = sender.view?.superview?.frame.origin else { return }
        var loc = convert(location, to: nil)
        self.delegate?.onloveButtonTapped(loc: loc, for: self)
    }

Now on my FeedController (which is UIcollectionViewController)

func likeButtonTapped(loc: CGPoint, for cell: PostUi){
            print("like button tapped")
            var touchLocation: CGPoint = loc
            print(touchLocation)
        ...
        ... //like implementation and checks
        ...

 var i = Int(location.x)
 var j = Int(location.y)

let path = UIBezierPath()

 path.move(to: CGPoint(x:i, y:j))
 //more code for animation

}

Now, when I tap on like button from the first post I the animation works but when I scroll down to another post and tap on like button, animation still works but can't be seen because it's happening on the top side. I get changed Coordinates for every like button but the path CGPoint starting is counted from the feed starting point. What should I do make it work correctly?

Body:
First thing is I don't get why do you pass the location to FeedController while you can do all the animation in UICollectionViewCell's Class. Is the animation happens with any other UIViews that is not inside the Post Cell (UICollectionViewCell)?

@IBAction func likeBtnTapped(_ sender: UIButton) {
    if post != nil {
        putLike(postId: post!.id, userId: user.id, isLiked: post!.liked)
    }
}

// Network Requests
func putLike(postId: Int, userId: Int, isLiked: Bool) {
    let httpService = HTTPService()
    httpService.putLikeRequest(postId: postId, userId: userId, isLiked: isLiked, onSuccess: { (liked, likeText) in
        self.post?.liked            = liked
        self.post?.likesText        = likeText
        if self.post != nil {
            self.likeCountLbl.text  = self.post!.likesText
            self.delegate?.replaceLikedPostInArray(post: self.post!)
            self.likeButtonScaleAnimation(liked: liked)
        }
    }) { (error) in
        print("putLikeRequest error : \(error)")
    }
}

func likeButtonScaleAnimation(liked: Bool) {
    UIView.animate(withDuration: 0.4,
                   animations: {
                    self.likeBtn.transform      = liked ? CGAffineTransform(scaleX: 1.4, y: 1.4)    : CGAffineTransform(scaleX: 0.6, y: 0.6)
                    self.likeBtn.tintColor      = liked ? UIColor.blue                              : UIColor.darkGray
                   },
                   completion: { _ in
                    UIView.animate(withDuration: 0.4) {
                        self.likeBtn.transform  = CGAffineTransform.identity
                        }
                  })
}


问:
Aligning a text and line parallel

There are 4 div's which has text and a line. The text will be coming from the service call and it may vary. The issue is that the line is not properly displayed it is of different length.The main condition is
1)All the line should end at the same point.
2)The line should be of 30px right from the margin and
3)The gap between the text and line should be 12px.

.about{
    display: inline-block;
}
hr{
  display:inline-block;
  width:200px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>

<div class="about">Chapter</div><hr/></div>
<div>
<div class="about">Learning Objectives</div><hr/></div>
<div>
<div class="about">Pages</div><hr/></div>
<div>
<div class="about">Sections</div><hr/></div></code>```

I tried with min,max-width but unable find a solution.Can anyone give a better solution?

答:
.about{
  display: inline-block;
}
hr{
  display: inline-block;
  width: 200px;
  margin-left: 10px;
  margin-bottom: 3px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>

<div class="about">Chapter</div><hr/></div>
<div>
<div class="about">Learning Objectives</div><hr/></div>
<div>
<div class="about">Pages</div><hr/></div>
<div>
<div class="about">hhhhhhhhhhhhhhh</div><hr/></div></code>```

Title: Aligning a text and line parallel

Body:
There are 4 div's which has text and a line. The text will be coming from the service call and it may vary. The issue is that the line is not properly displayed it is of different length.The main condition is
1)All the line should end at the same point.
2)The line should be of 30px right from the margin and
3)The gap between the text and line should be 12px.

.about{
    display: inline-block;
}
hr{
  display:inline-block;
  width:200px;
}

Chapter

Learning Objectives

Pages

Sections

I tried with min,max-width but unable find a solution.Can anyone give a better solution?

Body:
.about{
  display: inline-block;
}
hr{
  display: inline-block;
  width: 200px;
  margin-left: 10px;
  margin-bottom: 3px;
}

<div>

<div class="about">Chapter</div><hr/></div>
<div>
<div class="about">Learning Objectives</div><hr/></div>
<div>
<div class="about">Pages</div><hr/></div>
<div>
<div class="about">hhhhhhhhhhhhhhh</div><hr/></div>


问:
What's wrong if compiler optimization is turned on in debug build?
Why is it necessary/recommended to turn off all compiler optimizations when debugging application?

Background

I'm working in an 8-bit micro controller (OKI 411) which has 15K usable code memory space for interrupt service routines + ROM region/window (const global variables) + code. We nearly eat up ~13K so it is very tempting to turn on maximum possible optimization during even debugging.

答:
The only thing I can think of is that it might make debugging more difficult.

Other than that, there should be no problems.


问:
How to split train and test dataset to X_Train y_train and X_Test y_Test?
So I successfully split my dataset into Train & Test in a ratio of 70:30
I used this:

```<code>df_glass['split'] = np.random.randn(df_glass.shape[0], 1)
msk = np.random.rand(len(df_glass)) <= 0.7
train = df_glass[msk]
test = df_glass[~msk]
print(train)
print(test)
</code>```

Now how do I split train and test to X_train and y_train and X_test and y_test
Such that, X denotes the features of the database and y denotes the response?

I need to do supervised learning and apply ML modules on X_Train and y_Train.

My database looks like this:
Database_snippet

答:
i guess you may found this useful to understand..</p>

```<code>import pandas as pd
from sklearn.cross_validation import train_test_split
from sklearn.linear_model import LinearRegression

#importing dataset
dataset = pd.read_csv('Salary_Data.csv')
x = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 1].values

#spliting the dataset into training and test set
x_train, x_test, y_train, y_test = train_test_split(x, y,
test_size=1/3, random_state=0)
</code>```

Body:
So I successfully split my dataset into Train & Test in a ratio of 70:30
I used this:

df_glass['split'] = np.random.randn(df_glass.shape[0], 1)
msk = np.random.rand(len(df_glass)) <= 0.7
train = df_glass[msk]
test = df_glass[~msk]
print(train)
print(test)

Now how do I split train and test to X_train and y_train and X_test and y_test
Such that, X denotes the features of the database and y denotes the response?

I need to do supervised learning and apply ML modules on X_Train and y_Train.

My database looks like this:
Database_snippet

Body:
i guess you may found this useful to understand..

import pandas as pd
from sklearn.cross_validation import train_test_split
from sklearn.linear_model import LinearRegression

#importing dataset
dataset = pd.read_csv('Salary_Data.csv')
x = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 1].values

#spliting the dataset into training and test set
x_train, x_test, y_train, y_test = train_test_split(x, y,
test_size=1/3, random_state=0)


问:
What's the difference between tabindex="false" and empty tabindex?
As per the title, what is the difference when I have tabIndex="false" versus having empty tabIndex? As a bonus, what's the difference with having tabIndex="false" versus tabIndex=false versus empty tabIndex?

For example:
tabIndex="false" /> versus tabIndex /> versus tabIndex=false />

I haven't been able to find any resource or stackoverflow question that sheds light on this scenario.

Thanks in advance~

答:
There is no difference.

As Xufox explains in a comment, tabindex can only have integers as values. This is indicated in the HTML specification:

The tabindex attribute, if specified, must have a value that is a valid integer.

Having tabindex (without a value), or tabindex="false" or tabindex=false is irrelevant as all of them will fail the rules for parsing integers (in steps 5, 7, and 7 respectively). In those cases, browsers will ignore the value and apply the logic that they apply by default to any element.

So all of the following would be treated equally:

```<code><input tabindex="false" />
<input tabindex=false />
<input tabindex="" />
<input tabindex />
<input />
</code>```

Body:
As per the title, what is the difference when I have tabIndex="false" versus having empty tabIndex? As a bonus, what's the difference with having tabIndex="false" versus tabIndex=false versus empty tabIndex?

For example:
 versus  versus

I haven't been able to find any resource or stackoverflow question that sheds light on this scenario.

Thanks in advance~

Body:
There is no difference.

As Xufox explains in a comment, tabindex can only have integers as values. This is indicated in the HTML specification:

The tabindex attribute, if specified, must have a value that is a valid integer.

Having tabindex (without a value), or tabindex="false" or tabindex=false is irrelevant as all of them will fail the rules for parsing integers (in steps 5, 7, and 7 respectively). In those cases, browsers will ignore the value and apply the logic that they apply by default to any element.

So all of the following would be treated equally:

<input tabindex="false" />
<input tabindex=false />
<input tabindex="" />
<input tabindex />
<input />


答:
Try this simple if,bonus: no loop :)

```<code>    $(".test").change(function() {

      if($('.test option:selected').is('[value="hide"]')) {
        $("#bb").prop("disabled", true)
      } else {
        $("#bb").prop("disabled", false)
      }
    })
</code>```

demo:

$(".test").change(function() {

  if ($('.test option:selected').is('[value="hide"]')) {
    $("#bb").prop("disabled", true)
  } else {
    $("#bb").prop("disabled", false)
  }

})```
<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>
<select class='test'>
<option value='open'>AA</option>
<option value='hide'>BB</option>
</select>

<select class='test'>
<option value='open'>AA</option>
<option value='hide'>BB</option>
</select>

<button id='bb'>test me</button></code>```

Body:
I have multiple select option. I want to check if any select has specific selected value then disable a button. is possible to do that ?

here the example :

<select class='test'>
<option value='open'>AA</option>
<option value='hide'>BB</option>
</select>

<select class='test'>
<option value='open'>AA</option>
<option value='hide'>BB</option>
</select>

<button id='bb'></button>

so if there is any select with class 'test' is selected with 'hide' value, then button with id 'bb' is disabled.
Even if I select another select option with open value, if there is still one select with hide value left, the button should still disabled.
I want to do that with jQuery.

Body:
Try this simple if,bonus: no loop :)

    $(".test").change(function() {

      if($('.test option:selected').is('[value="hide"]')) {
        $("#bb").prop("disabled", true)
      } else {
        $("#bb").prop("disabled", false)
      }
    })

demo:

$(".test").change(function() {

  if ($('.test option:selected').is('[value="hide"]')) {
    $("#bb").prop("disabled", true)
  } else {
    $("#bb").prop("disabled", false)
  }

})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class='test'>
<option value='open'>AA</option>
<option value='hide'>BB</option>
</select>

<select class='test'>
<option value='open'>AA</option>
<option value='hide'>BB</option>
</select>

<button id='bb'>test me</button>


问:
How do I make a splash screen?
I want my app to look more professional, so I decided to add a splash screen.

How should I go about the implementation?

答:
In my case I didn't want to create a new Activity only to show a image for 2 seconds. When starting my MainAvtivity, images gets loaded into holders using picasso, I know that this takes about 1 second to load so I decided to do the following inside my MainActivity OnCreate:

```<code>splashImage = (ImageView) findViewById(R.id.spllll);

    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

    int secondsDelayed = 1;
    new Handler().postDelayed(new Runnable() {
        public void run() {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            splashImage.setVisibility(View.GONE);

        }
    }, secondsDelayed * 2000);
</code>```

When starting the application the first thing that happens is the ImageView gets displayed and the statusBar is removed by setting the window flags to full screen. Then I used a Handler to run for 2 seconds, after the 2 seconds I clear the full screen flags and set the visibility of the ImageView to GONE. Easy, simple, effective.

Title: How do I make a splash screen?

Body:
In my case I didn't want to create a new Activity only to show a image for 2 seconds. When starting my MainAvtivity, images gets loaded into holders using picasso, I know that this takes about 1 second to load so I decided to do the following inside my MainActivity OnCreate:

splashImage = (ImageView) findViewById(R.id.spllll);

    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

    int secondsDelayed = 1;
    new Handler().postDelayed(new Runnable() {
        public void run() {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            splashImage.setVisibility(View.GONE);

        }
    }, secondsDelayed * 2000);

When starting the application the first thing that happens is the ImageView gets displayed and the statusBar is removed by setting the window flags to full screen. Then I used a Handler to run for 2 seconds, after the 2 seconds I clear the full screen flags and set the visibility of the ImageView to GONE. Easy, simple, effective.