问:
"HTTP Status 405 – HTTP method GET is not supported by this URL" error when calling servlet from JSP
I have the following code, but when I try to access the /data-upload URL I get the error "HTTP method GET is not supported by this URL".

Java servlet code:

```<code>package xyz.controllers;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.entity.StringEntity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.annotation.WebServlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

@WebServlet("/data-upload")
public class GetLocalAreaIds extends HttpServlet {

    // HTTP POST request
    public void doPost(HttpServletRequest request, HttpResponse response) throws ServletException, IOException {
        System.out.println("#VH in doPost method ");
        String url = "http://xyz.xyz/search";

        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);

        // add header
        post.setHeader("Content-Type", "application/xml");

        String elementLocalNameType = request.getParameter("elementLocalNameType");
        System.out.println("#VH elementLocalNameType: " + elementLocalNameType);

        String localAreaName = request.getParameter("localAreaName");
        System.out.println("#VH localAreaName: " + localAreaName);

        StringEntity params = null;
        try {
            params = getStringEntityParams(elementLocalNameType, localAreaName);
            System.out.println("#VH params: " + params);
        }
        catch (Exception e) {
            System.out.println("Error while getting elementLocalNameType");
        }

        post.setEntity(params);
        response = client.execute(post);
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + post.getEntity());
        System.out.println("Response Code : " +
                response.getStatusLine().getStatusCode());

        BufferedReader rd = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent()));

        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }

        System.out.println("#VH result.toString(): " + result.toString());
    }

    public void doGet(HttpServletRequest request, HttpResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    private StringEntity getStringEntityParams(String elementLocalNameType, String localAreaName) throws Exception {
        StringEntity params = new StringEntity("<request><workflow>get-element-values-workflow</workflow><get-element-values><element-localname>"+elementLocalNameType+"</element-localname><starts-with>"+localAreaName+"</starts-with><is-csv>True</is-csv></get-element-values></request>");
        return params;
    }
}
</code>```

JSP code:

```<code><%@ taglib prefix="tiles" uri="http://tiles.apache.org/tags-tiles" %>
<%@ taglib prefix="user" uri="/WEB-INF/tlds/user.tld" %>

<%@ page import="org.apache.http.client.HttpClient" %>
<%@ page import="org.apache.http.client.methods.HttpGet" %>
<%@ page import="org.apache.http.impl.client.DefaultHttpClient" %>
<%@ page import="GetLocalAreaIds" %>

<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>

<tiles:insertDefinition name="layout">
    <tiles:putAttribute name="title">Title</tiles:putAttribute>

  <tiles:putAttribute name="main">

        <main id="content" role="main" class="group category-page">
            <header class="page-header group">
                <div class="full-width">
                    <h1>Data Upload</h1>
                </div>
            </header>

            <div class="browse-container full-width group">
                        <div id="error">
                        <p style="color: #ff0000">${error}</p>
                </div>

                <user:current-local-area msg="<b>LA:</b> !{#localAreaName}"/>

                <c:set var = 'la_id' scope = 'session' value = '<user:current-local-area msg="!{#localAreaName}">'/>

                <c:set var = "la_id"><user:current-local-area msg="!{#localAreaName}"/></c:set>

                <jsp:useBean id="GetLocalAreaIds" class="GetLocalAreaIds"/>

                <form action="${pageContext.request.contextPath}/data-upload" method="POST">
                  <span>Do you want to download the LA IDs for families or individuals?</span><br />
                  <input type="radio" name="elementLocalNameType" value="la-family-id"> Family IDs<br />
                  <input type="radio" name="elementLocalNameType" value="la-individual-id"> Individual IDs<br />
                  <input type="hidden" name="localAreaName" value="${la_id}">
                  <input class="button" type="submit" value="Submit">
                </form>

            </div>

        </main>
        </tiles:putAttribute>
  </tiles:insertDefinition>
</code>```

I have read some of the other posts which deal with the same issue, but their solutions didn't work for me.  When I try adding @Override to the doPost and doGet methods, I get an error saying "method does not override or implement a method from a supertype" even though I'm extending HttpServlet.

答:
The issue is, both get and post are not inherited from the HttpServlet
change the

```<code>doPost(HttpServletRequest request, HttpResponse response)
</code>```

to

```<code>doPost(HttpServletRequest request, HttpServletResponse response)
</code>```

and

```<code>doGet(HttpServletRequest request, HttpResponse response)
</code>```

to

```<code>doGet(HttpServletRequest request, HttpServletResponse response)
</code>```

EDIT
Next issue is

```<code>response = client.execute(post);
</code>```

which as you stated "incompatible types: org.apache.http.HttpResponse cannot be converted to javax.servlet.http.HttpServletResponse"

Change it to

```<code>org.apache.http.HttpResponse my_response = client.execute(post);
...
System.out.println("Response Code : " +
                my_response.getStatusLine().getStatusCode());

        BufferedReader rd = new BufferedReader(
                new InputStreamReader(my_response.getEntity().getContent()));
</code>```

Also note, you don't write anything to user response out, so if you get nothing in calling client(e.g. browser) it's normal. Or you write everything you do with stdout with response out.

Body:
I have the following code, but when I try to access the /data-upload URL I get the error "HTTP method GET is not supported by this URL".

Java servlet code:

package xyz.controllers;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.entity.StringEntity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.annotation.WebServlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

@WebServlet("/data-upload")
public class GetLocalAreaIds extends HttpServlet {

    // HTTP POST request
    public void doPost(HttpServletRequest request, HttpResponse response) throws ServletException, IOException {
        System.out.println("#VH in doPost method ");
        String url = "http://xyz.xyz/search";

        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);

        // add header
        post.setHeader("Content-Type", "application/xml");

        String elementLocalNameType = request.getParameter("elementLocalNameType");
        System.out.println("#VH elementLocalNameType: " + elementLocalNameType);

        String localAreaName = request.getParameter("localAreaName");
        System.out.println("#VH localAreaName: " + localAreaName);

        StringEntity params = null;
        try {
            params = getStringEntityParams(elementLocalNameType, localAreaName);
            System.out.println("#VH params: " + params);
        }
        catch (Exception e) {
            System.out.println("Error while getting elementLocalNameType");
        }

        post.setEntity(params);
        response = client.execute(post);
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + post.getEntity());
        System.out.println("Response Code : " +
                response.getStatusLine().getStatusCode());

        BufferedReader rd = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent()));

        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }

        System.out.println("#VH result.toString(): " + result.toString());
    }

    public void doGet(HttpServletRequest request, HttpResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    private StringEntity getStringEntityParams(String elementLocalNameType, String localAreaName) throws Exception {
        StringEntity params = new StringEntity("<request><workflow>get-element-values-workflow</workflow><get-element-values><element-localname>"+elementLocalNameType+"</element-localname><starts-with>"+localAreaName+"</starts-with><is-csv>True</is-csv></get-element-values></request>");
        return params;
    }
}

JSP code:

<%@ taglib prefix="tiles" uri="http://tiles.apache.org/tags-tiles" %>
<%@ taglib prefix="user" uri="/WEB-INF/tlds/user.tld" %>

<%@ page import="org.apache.http.client.HttpClient" %>
<%@ page import="org.apache.http.client.methods.HttpGet" %>
<%@ page import="org.apache.http.impl.client.DefaultHttpClient" %>
<%@ page import="GetLocalAreaIds" %>

<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>

<tiles:insertDefinition name="layout">
    <tiles:putAttribute name="title">Title</tiles:putAttribute>

  <tiles:putAttribute name="main">

Data Upload

${error}

                <user:current-local-area msg="LA: !{#localAreaName}"/>

                <c:set var = 'la_id' scope = 'session' value = '<user:current-local-area msg="!{#localAreaName}">'/>

                <c:set var = "la_id"><user:current-local-area msg="!{#localAreaName}"/></c:set>

                <jsp:useBean id="GetLocalAreaIds" class="GetLocalAreaIds"/>

                <form action="${pageContext.request.contextPath}/data-upload" method="POST">
                  Do you want to download the LA IDs for families or individuals?

                  <input type="radio" name="elementLocalNameType" value="la-family-id"> Family IDs

                  <input type="radio" name="elementLocalNameType" value="la-individual-id"> Individual IDs

                  <input type="hidden" name="localAreaName" value="${la_id}">
                  <input class="button" type="submit" value="Submit">
                </form>

        </tiles:putAttribute>
  </tiles:insertDefinition>

I have read some of the other posts which deal with the same issue, but their solutions didn't work for me.  When I try adding @Override to the doPost and doGet methods, I get an error saying "method does not override or implement a method from a supertype" even though I'm extending HttpServlet.

Body:
The issue is, both get and post are not inherited from the HttpServlet
change the

doPost(HttpServletRequest request, HttpResponse response)

to

doPost(HttpServletRequest request, HttpServletResponse response)

and

doGet(HttpServletRequest request, HttpResponse response)

to

doGet(HttpServletRequest request, HttpServletResponse response)

EDIT
Next issue is

response = client.execute(post);

which as you stated "incompatible types: org.apache.http.HttpResponse cannot be converted to javax.servlet.http.HttpServletResponse"

Change it to

org.apache.http.HttpResponse my_response = client.execute(post);
...
System.out.println("Response Code : " +
                my_response.getStatusLine().getStatusCode());

        BufferedReader rd = new BufferedReader(
                new InputStreamReader(my_response.getEntity().getContent()));

Also note, you don't write anything to user response out, so if you get nothing in calling client(e.g. browser) it's normal. Or you write everything you do with stdout with response out.


来源: stackexchange

问:
How to concatenate some read-only text at the end of the text box?
How to make only some text in a text-box read-only while allowing the rest to be edited. I'm trying to make a text box that allow user to input text and then there is some read-only text (non-editable) at the end of the text box. How can I do this in Javascript/jquery?

Eg of an input field:

DELIVERY ADDRESS

Enter your home or apartment number, ABC Area, XYZ Town

In above eg user is asked to provide home or apartment number and ABC Area, XYZ Town is a predefined value (already provided at some stage). If I split them in 2, most user put their complete address in the text field resulting in duplication of data. I  need to avoid this duplication.

Thanks a mill in advance for your help.

答:
There isn't possible solution for you to do for such case.

For better user experiences, I would suggest you to put editable text in a text box, and non-editable words in labels. In will help to not make user confuses.

ContentLicense: CC BY-SA 3.0


问:
Trying to stop removing `div` if it's length at `0` or `1`. can someone help me?
Trying to stop removing div if it's length at 0 or 1. can someone help me?

Here is link: https://jsfiddle.net/Issact/ncqnv8zs/

HTML & JS:

$(document).ready(function() {

  $('.div').click(function() {
    $(this).remove();
    var divLength = $('.main div').length;
    $('.mainLength').text(divLength + " " + 'divs');

    if (divLength === 1) {
      $(this).stop().remove();
    }

  });
});```
<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>
<div class="main">
  <div class="div">Div one</div>
  <div class="div">Div Two</div>
  <div class="div">Div Three</div>
  <div class="div">Div Four</div>
</div>

<div class="mainLength">
</div></code>```

答:
You must check div length before removing a div element.</p>

```<code> $(document).ready(function () {

            $('.div').click(function () {

                var divLength = $('.main div').length;
                if (divLength > 1) {
                    $(this).remove();
                    $('.mainLength').text(divLength - 1 + " " + 'divs');
                    //$(this).stop().remove();
                }

            });
        });
</code>```

Body:
Trying to stop removing div if it's length at 0 or 1. can someone help me?

Here is link: https://jsfiddle.net/Issact/ncqnv8zs/

HTML & JS:

$(document).ready(function() {

  $('.div').click(function() {
    $(this).remove();
    var divLength = $('.main div').length;
    $('.mainLength').text(divLength + " " + 'divs');

    if (divLength === 1) {
      $(this).stop().remove();
    }

  });
});

Div one

Div Two

Div Three

Div Four

Body:
You must check div length before removing a div element.

 $(document).ready(function () {

            $('.div').click(function () {

                var divLength = $('.main div').length;
                if (divLength > 1) {
                    $(this).remove();
                    $('.mainLength').text(divLength - 1 + " " + 'divs');
                    //$(this).stop().remove();
                }

            });
        });


问:
Mysql column with null values - what are the space requirements?
I have a table with quite a lot entries.
I need an additional column with an integer value or null.
The thing is that only very few rows will have that field populated.

So i wonder whether its better to create a seperate table where i link the entries in an 1:1 relation.

I know one integer entry takes 4 bytes in mysql/myisam. If I have the column set to allow null values, and only 100 of 100 000 rows have the field populated, will the rest still consume 4 bytes for every null value?

Or is mysql intelligent enough to set the value where it is populated and just regard everything as null, where nothing is set?

答:
This depends on the ROW_FORMAT value you give when you create your table.

Before version 5.0.3, the default format is set to "REDUNDANT" : any fixed-length field will use the same space, even if it's value is NULL.

Starting with version 5.0.3, the value is set to "COMPACT" : NULL values will never use any space in your database.

You can do an ALTER TABLE to be sure to use the correct format :

```<code>ALTER TABLE ... ROW_FORMAT=COMPACT
</code>```

More details here :
http://dev.mysql.com/doc/refman/5.1/en/data-size.html

ContentLicense: CC BY-SA 2.5

Body:
This depends on the ROW_FORMAT value you give when you create your table.

Before version 5.0.3, the default format is set to "REDUNDANT" : any fixed-length field will use the same space, even if it's value is NULL.

Starting with version 5.0.3, the value is set to "COMPACT" : NULL values will never use any space in your database.

You can do an ALTER TABLE to be sure to use the correct format :

ALTER TABLE ... ROW_FORMAT=COMPACT

More details here :
http://dev.mysql.com/doc/refman/5.1/en/data-size.html


问:
Add social icons to footer in mobile
I want to add social icons in the footer of my mobile application (Facebook, Youtube, Twitter, Whatsapp). I'm using xamarin cross platform to build my application.

答:
A mobile app doesn't really have a footer of sorts, and putting social icons in it seems more like a thing you would do on a website to me. However, it is fairly easy to create an element that is always at the bottom of the page. You could use a StackLayout with VerticalOptions set to EndAndExpand which will vertically put it at the bottom or you could create a Grid structure to ensure the content is always at the bottom.

```<code><Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <Grid Grid.Row="0">
        // Normal content
    </Grid>
    <Grid Grid.Row="1">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Button Grid.Column="0" Text="Twitter" />
        <Button Grid.Column="1" Text="Facebook" />
    </Grid>
</Grid>
</code>```

Title: Add social icons to footer in mobile

Body:
A mobile app doesn't really have a footer of sorts, and putting social icons in it seems more like a thing you would do on a website to me. However, it is fairly easy to create an element that is always at the bottom of the page. You could use a StackLayout with VerticalOptions set to EndAndExpand which will vertically put it at the bottom or you could create a Grid structure to ensure the content is always at the bottom.

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <Grid Grid.Row="0">
        // Normal content
    </Grid>
    <Grid Grid.Row="1">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Button Grid.Column="0" Text="Twitter" />
        <Button Grid.Column="1" Text="Facebook" />
    </Grid>
</Grid>


问:
How to unselect multiple UITableview cell by tapping the selected button again

Hi, I wanted to select multiple UITableViewCells and unselect any by tapping again.

Following are my codes of didSelectRowAtIndexPath: and cellForRowAtIndexPath:

```<code>-(UITableViewCell *)tableView:(UITableView *)tableView
   cellForRowAtIndexPath:(NSIndexPath *)indexPath
   {
NSString *cellIdentifier = @"serviceTypeSelectionCell";
ServiceTypeSelectionTableViewCell *serviceTypeCell = (ServiceTypeSelectionTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (serviceTypeCell == nil)
{
    serviceTypeCell = [[ServiceTypeSelectionTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
//serviceDetailsCell.noOfQuantityTextField.tag = indexPath.row;
serviceTypeCell.serviceTypeNameLabel.text = [NSString stringWithFormat:@"%@",arrayOfServiceTypes[indexPath.row][@"sub_cat_name"]];

if([[arrayOfSelectedBoolValues objectAtIndex:indexPath.row] boolValue])
{
    serviceTypeCell.serviceTypeImageView.image = [UIImage imageNamed:@"cancellation_reason_correct_icon"];
}
else {
    serviceTypeCell.serviceTypeImageView.image = [UIImage imageNamed:@"cancellation_reason_unselect_icon"];
}
return serviceTypeCell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
for (int i = 0; i < [arrayOfServiceTypes count]; i++)//Make all Rows To UnSelected
{
   [arrayOfSelectedBoolValues replaceObjectAtIndex:i withObject:[NSNumber numberWithBool:NO]];
}
[arrayOfSelectedBoolValues addObjectsFromArray:sele:indexPath.row];
if(arrayOfSelectedBoolValues!=nil)
{
    [arrayOfSelectedBoolValues replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:YES]];
}

    [arrayOfSelectedBoolValues replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:YES]];
{
[self.tableView reloadData];
[self showOrHideAddButton];
}
</code>```

I have an existing code of single select and unselect of the above uitableview. And I can get multiple selection only by disabling all the above code and keep this part in didSelectRowAtIndexPath:.

```<code>-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
 [arrayOfSelectedBoolValues replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:YES]];
    [self.tableView reloadData];
    [self showOrHideAddButton];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.doneButton.hidden = YES;
    arrayOfSelectedBoolValues = [[NSMutableArray alloc]init];

    for (int i = 0; i < [arrayOfServiceTypes count]; i++)
    {
        // [arrayOfexpOrCollBoolValues addObject:[NSNumber numberWithBool:NO]];
        [arrayOfSelectedBoolValues addObject:[NSNumber numberWithBool:NO]];
    }
    [self sendServiceToGetServiceTypes];
}
</code>```

so please anyone post a structured code according to my code to select multiple tableviewcells and unselect any cells by tapping again before send selected values to the server.

Thanks in Advance.

答:
You need to maintain an array of rows you select, based on that you will either select a row or will deselect row(if it already exists in that array). Would look something like this:

Swift 3 Code:

```<code>var selectedArray : [IndexPath] = [IndexPath]()

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let myCell = tableView.cellForRow(at: indexPath) as! TableCell

    if(!selectedArray.contains(indexPath))
    {
        selectedArray.append(indexPath)
        // Change cell image for selected if needed here.
    }
    else
    {
        // remove from array here if required
        // Change cell image for un selected if needed here.
    }
}
</code>```

Objc Code:

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

.
.
.
if(![selectedArray containsObject:indexPath])
{
    [selectedArray addObject:indexPath];
    // Change cell image for selected if needed here.
}
else
{
    [selectedArray removeObject:indexPath];
    // remove from array here if required
    // Change cell image for un selected if needed here.
}
.
.
.
}
</code>```

Declare selectedArray in .h file (in interface) and initialize it in viewDidLoad like so - selectedArray = [[NSMutableArray alloc]init];

Body:
Hi, I wanted to select multiple UITableViewCells and unselect any by tapping again.

Following are my codes of didSelectRowAtIndexPath: and cellForRowAtIndexPath:

-(UITableViewCell *)tableView:(UITableView *)tableView
   cellForRowAtIndexPath:(NSIndexPath *)indexPath
   {
NSString *cellIdentifier = @"serviceTypeSelectionCell";
ServiceTypeSelectionTableViewCell *serviceTypeCell = (ServiceTypeSelectionTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (serviceTypeCell == nil)
{
    serviceTypeCell = [[ServiceTypeSelectionTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
//serviceDetailsCell.noOfQuantityTextField.tag = indexPath.row;
serviceTypeCell.serviceTypeNameLabel.text = [NSString stringWithFormat:@"%@",arrayOfServiceTypes[indexPath.row][@"sub_cat_name"]];

if([[arrayOfSelectedBoolValues objectAtIndex:indexPath.row] boolValue])
{
    serviceTypeCell.serviceTypeImageView.image = [UIImage imageNamed:@"cancellation_reason_correct_icon"];
}
else {
    serviceTypeCell.serviceTypeImageView.image = [UIImage imageNamed:@"cancellation_reason_unselect_icon"];
}
return serviceTypeCell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
for (int i = 0; i < [arrayOfServiceTypes count]; i++)//Make all Rows To UnSelected
{
   [arrayOfSelectedBoolValues replaceObjectAtIndex:i withObject:[NSNumber numberWithBool:NO]];
}
[arrayOfSelectedBoolValues addObjectsFromArray:sele:indexPath.row];
if(arrayOfSelectedBoolValues!=nil)
{
    [arrayOfSelectedBoolValues replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:YES]];
}

    [arrayOfSelectedBoolValues replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:YES]];
{
[self.tableView reloadData];
[self showOrHideAddButton];
}

I have an existing code of single select and unselect of the above uitableview. And I can get multiple selection only by disabling all the above code and keep this part in didSelectRowAtIndexPath:.

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
 [arrayOfSelectedBoolValues replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:YES]];
    [self.tableView reloadData];
    [self showOrHideAddButton];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.doneButton.hidden = YES;
    arrayOfSelectedBoolValues = [[NSMutableArray alloc]init];

    for (int i = 0; i < [arrayOfServiceTypes count]; i++)
    {
        // [arrayOfexpOrCollBoolValues addObject:[NSNumber numberWithBool:NO]];
        [arrayOfSelectedBoolValues addObject:[NSNumber numberWithBool:NO]];
    }
    [self sendServiceToGetServiceTypes];
}

so please anyone post a structured code according to my code to select multiple tableviewcells and unselect any cells by tapping again before send selected values to the server.

Thanks in Advance.

Body:
You need to maintain an array of rows you select, based on that you will either select a row or will deselect row(if it already exists in that array). Would look something like this:

Swift 3 Code:

var selectedArray : [IndexPath] = [IndexPath]()

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let myCell = tableView.cellForRow(at: indexPath) as! TableCell

    if(!selectedArray.contains(indexPath))
    {
        selectedArray.append(indexPath)
        // Change cell image for selected if needed here.
    }
    else
    {
        // remove from array here if required
        // Change cell image for un selected if needed here.
    }
}

Objc Code:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

.
.
.
if(![selectedArray containsObject:indexPath])
{
    [selectedArray addObject:indexPath];
    // Change cell image for selected if needed here.
}
else
{
    [selectedArray removeObject:indexPath];
    // remove from array here if required
    // Change cell image for un selected if needed here.
}
.
.
.
}

Declare selectedArray in .h file (in interface) and initialize it in viewDidLoad like so - selectedArray = [[NSMutableArray alloc]init];


问:
Are disposable fields of disposable classes disposed of automatically
My question is fairly straightforward: If a class that implements IDisposable has fields which are also disposable, will disposing of the instance also dispose of the field values?

Example:

Say I have a class, OuterDisposable, which has a field innerDisposable, who's type is another disposable class:

```<code>public class OuterDisposable : IDisposable
{
    private InnerDisposable innerDisposable;
}
</code>```

I intend to wrap all instances of OuterDisposable in a using statement so that they are disposed of automatically and safely:

```<code>using (var outerDisposable = new OuterDisposable())
{
    // Stuff
}
</code>```

However, I'm not sure what will happen to innerDisposable once the end of the using is reached. It is very important that it is disposed of correctly, so I need to be sure what the behavior will be.

I presume explicitly disposing of innerDisposable will achieve my desired result:

```<code>public void Dispose()
{
    this.innerDisposable.Dispose();
}
</code>```

But is this necessary? If the outer using statement takes care of disposing innerDisposable as well as outerDisposable, then it is redundant.

So, how are such disposable fields handled?

答:
IDisposable is an interface and a pattern. It's not really part of the C# language, outside of explicit support in using and foreach. Nothing happens "automatically".

Consider, contrariwise, if this disposal did happen automatically. And consider further that it's perfectly valid for a class to hold a reference to a shared resource of some kind that may be disposable. You would have to invent new syntax to then be able to "opt out" of this automatic disposal that you were looking for.

C# is a simpler language by not having such a feature. It's always your responsibility to clean up IDisposable objects at a time when you, the programmer, know that they're no longer being used. Often, for a class such as the one here, that will be when your own Dispose method is being called.

Body:
My question is fairly straightforward: If a class that implements IDisposable has fields which are also disposable, will disposing of the instance also dispose of the field values?

Example:

Say I have a class, OuterDisposable, which has a field innerDisposable, who's type is another disposable class:

public class OuterDisposable : IDisposable
{
    private InnerDisposable innerDisposable;
}

I intend to wrap all instances of OuterDisposable in a using statement so that they are disposed of automatically and safely:

using (var outerDisposable = new OuterDisposable())
{
    // Stuff
}

However, I'm not sure what will happen to innerDisposable once the end of the using is reached. It is very important that it is disposed of correctly, so I need to be sure what the behavior will be.

I presume explicitly disposing of innerDisposable will achieve my desired result:

public void Dispose()
{
    this.innerDisposable.Dispose();
}

But is this necessary? If the outer using statement takes care of disposing innerDisposable as well as outerDisposable, then it is redundant.

So, how are such disposable fields handled?


问:
Navigate to url from local page of a Chrome Extension
I'm trying to create a chrome extension to stop myself from accessing certain pages too much, for example facebook. The idea is to have the extension blocks when I access facebook, but it still has an option for me to continue going to facebook.

Right now I'm using a background script to block it just fine.

```<code>chrome.webNavigation.onBeforeNavigate.addListener(function(e) {
  chrome.tabs.query({currentWindow: true, active: true}, function (tab) {
    chrome.tabs.update(tab.id, {url: 'waster.html'});
  });
  }, {url: [{hostSuffix: 'facebook.com'}]}
);
</code>```

In waster.html I have a link to go to facebook. However, the issue is when I click that link, it trigger the same event again, then it gets blocked.

Is there anyway to workaround this? Like maybe pass parameter through the link to avoid blocking?

Thanks

==
Edit:
Add more details

The purpose is to block facebook.com, so I added a event listener to onBeforeNavigate with "facebook.com" in filter to stop the page before loading, to load my own page waster.html.
However in waster.html I want to have a link to allow users to go to facebook.

The issue comes from here, since when I click the link, it triggeers the event again, and well, blocks it again.

答:
I messed around a bit and it works now though I don't fully understand why yet

```<code>chrome.webNavigation.onBeforeNavigate.addListener(function(e) {
  var url = new URL(e.url);
    if (url.hostname == 'facebook.com') {
        chrome.tabs.update(e.tabId, {url: 'waster.html'});
    }
  }, {url: [{hostSuffix: 'facebook.com'}]}
);
</code>```

And in waster.html, instead of normal link with , I need to use following js:

```<code>$("#slack-time").click(function(e){
    e.preventDefault();
    chrome.tabs.query({currentWindow: true, active: true}, function (tab) {
              chrome.tabs.update(tab.id, {url: 'http://www.facebook.com'});
        });
})
</code>```

Body:
I'm trying to create a chrome extension to stop myself from accessing certain pages too much, for example facebook. The idea is to have the extension blocks when I access facebook, but it still has an option for me to continue going to facebook.

Right now I'm using a background script to block it just fine.

chrome.webNavigation.onBeforeNavigate.addListener(function(e) {
  chrome.tabs.query({currentWindow: true, active: true}, function (tab) {
    chrome.tabs.update(tab.id, {url: 'waster.html'});
  });
  }, {url: [{hostSuffix: 'facebook.com'}]}
);

In waster.html I have a link to go to facebook. However, the issue is when I click that link, it trigger the same event again, then it gets blocked.

Is there anyway to workaround this? Like maybe pass parameter through the link to avoid blocking?

Thanks

==
Edit:
Add more details

The purpose is to block facebook.com, so I added a event listener to onBeforeNavigate with "facebook.com" in filter to stop the page before loading, to load my own page waster.html.
However in waster.html I want to have a link to allow users to go to facebook.

The issue comes from here, since when I click the link, it triggeers the event again, and well, blocks it again.

Body:
I messed around a bit and it works now though I don't fully understand why yet

chrome.webNavigation.onBeforeNavigate.addListener(function(e) {
  var url = new URL(e.url);
    if (url.hostname == 'facebook.com') {
        chrome.tabs.update(e.tabId, {url: 'waster.html'});
    }
  }, {url: [{hostSuffix: 'facebook.com'}]}
);

And in waster.html, instead of normal link with <a>, I need to use following js:

$("#slack-time").click(function(e){
    e.preventDefault();
    chrome.tabs.query({currentWindow: true, active: true}, function (tab) {
              chrome.tabs.update(tab.id, {url: 'http://www.facebook.com'});
        });
})


问:
how can i access the value of each data from this json?
```<code>{
    "sachin.company": {
        "classkey": "dotcompany",
        "status": "available"
    },
    "sachin.com": {
        "classkey": "domcno",
        "status": "regthroughothers"
    },
    "sachin.co.in": {
        "classkey": "thirdleveldotin",
        "status": "regthroughothers"
    },
   "sachin.org": {
        "classkey": "domorg",
        "status": "regthroughothers"
    },
    "sachin.guru": {
        "classkey": "dotguru",
        "status": "available"
    },
    "sachin.sexy": {
        "classkey": "dotsexy",
        "status": "available"
    },
    "sachin.nettlds=asia": {
        "status": "unknown"
    }
}
</code>```

I want to access the classKey and status from this object.
how can I access for each of keys value?
I tried this var keys = Object.keys(response); but this only create the array like ["sachin.company", "sachin.in", "sachin.community", "sachin.com", "sachin.computer", "sachin.co.in", "sachin.org", "sachin.compare", "sachin.net"]

答:
```<code>Object.keys(parsedJson).forEach(function(value){
    var classKey = parsedJson[value].classKey;
    var status = parsedJson[value].status;
    //do whatever you want with them
});
</code>```

Body:
{
    "sachin.company": {
        "classkey": "dotcompany",
        "status": "available"
    },
    "sachin.com": {
        "classkey": "domcno",
        "status": "regthroughothers"
    },
    "sachin.co.in": {
        "classkey": "thirdleveldotin",
        "status": "regthroughothers"
    },
   "sachin.org": {
        "classkey": "domorg",
        "status": "regthroughothers"
    },
    "sachin.guru": {
        "classkey": "dotguru",
        "status": "available"
    },
    "sachin.sexy": {
        "classkey": "dotsexy",
        "status": "available"
    },
    "sachin.nettlds=asia": {
        "status": "unknown"
    }
}

I want to access the classKey and status from this object.
how can I access for each of keys value?
I tried this var keys = Object.keys(response); but this only create the array like ["sachin.company", "sachin.in", "sachin.community", "sachin.com", "sachin.computer", "sachin.co.in", "sachin.org", "sachin.compare", "sachin.net"]


问:
Can't figure out why scrollview is not scrolling
I'm making a simple converter app. Trying to convert input and display it in the EditTexts below but my ScrollView doesnt work.(Literally does nothing) I use ConstraintLayout as root and I have LinearLayout inside it which is the root of ScrollView.

So, What am I missing here?

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="gns.converter.LengthConversion">

    <Spinner
        android:id="@+id/spinnerTo"
        android:layout_width="120dp"
        android:entries="@array/spinnerLengthItems"
        android:layout_height="wrap_content"
        app:layout_constraintLeft_toRightOf="@+id/textFrom"
        android:layout_marginLeft="42dp"
        app:layout_constraintBaseline_toBaselineOf="@+id/textFrom"
        android:layout_marginStart="42dp" />

    <EditText
        android:id="@+id/textFrom"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="number"
        android:textSize="20sp"
        android:hint="(From) 0"
        android:gravity="right"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="44dp"
        android:layout_marginLeft="16dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginStart="16dp" />

    <Button
        android:id="@+id/buttonConvert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="78dp"
        android:layout_marginTop="13dp"
        android:text="CONVERT"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textFrom"
        android:layout_marginStart="78dp" />

    <Button
        android:id="@+id/buttonClear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="42dp"
        android:layout_marginTop="23dp"
        android:text="CLEAR"
        app:layout_constraintLeft_toRightOf="@+id/buttonConvert"
        app:layout_constraintTop_toBottomOf="@+id/spinnerTo"
        android:layout_marginStart="42dp" />

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="495dp"
        android:orientation="horizontal"
        android:layout_marginRight="8dp"
        android:background="#e40707"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginTop="30dp"
        app:layout_constraintTop_toBottomOf="@+id/buttonConvert"
        app:layout_constraintHorizontal_bias="0.0">

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="fill_parent"
            >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">

                <EditText
                    android:id="@+id/editText2"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:ems="10"
                    android:inputType="textPersonName"
                    android:text="Name" />

                <EditText
                    android:id="@+id/editText3"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:ems="10"
                    android:inputType="textPersonName"
                    android:text="Name" />

                <EditText
                    android:id="@+id/editText4"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:ems="10"
                    android:inputType="textPersonName"
                    android:text="Name" />

                <EditText
                    android:id="@+id/editText5"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:ems="10"
                    android:inputType="textPersonName"
                    android:text="Name" />

                <EditText
                    android:id="@+id/editText6"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:ems="10"
                    android:inputType="textPersonName"
                    android:text="Name" />

                <EditText
                    android:id="@+id/editText7"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:ems="10"
                    android:inputType="textPersonName"
                    android:text="Name" />

                <EditText
                    android:id="@+id/editText8"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:ems="10"
                    android:inputType="textPersonName"
                    android:text="Name" />

                <EditText
                    android:id="@+id/editText9"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:ems="10"
                    android:inputType="textPersonName"
                    android:text="Name" />
            </LinearLayout>

        </ScrollView>
    </LinearLayout>

</android.support.constraint.ConstraintLayout>
</code>```

答:
try this make your scroll view android:fillViewport="true"

```<code><ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">

 <LinearLayout
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:orientation="vertical">
  // add here all your controls
</LinearLayout>

</ScrollView>
</code>```

Body:
I'm making a simple converter app. Trying to convert input and display it in the EditTexts below but my ScrollView doesnt work.(Literally does nothing) I use ConstraintLayout as root and I have LinearLayout inside it which is the root of ScrollView.

So, What am I missing here?

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="gns.converter.LengthConversion">

    <Spinner
        android:id="@+id/spinnerTo"
        android:layout_width="120dp"
        android:entries="@array/spinnerLengthItems"
        android:layout_height="wrap_content"
        app:layout_constraintLeft_toRightOf="@+id/textFrom"
        android:layout_marginLeft="42dp"
        app:layout_constraintBaseline_toBaselineOf="@+id/textFrom"
        android:layout_marginStart="42dp" />

    <EditText
        android:id="@+id/textFrom"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="number"
        android:textSize="20sp"
        android:hint="(From) 0"
        android:gravity="right"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="44dp"
        android:layout_marginLeft="16dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginStart="16dp" />

    <Button
        android:id="@+id/buttonConvert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="78dp"
        android:layout_marginTop="13dp"
        android:text="CONVERT"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textFrom"
        android:layout_marginStart="78dp" />

    <Button
        android:id="@+id/buttonClear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="42dp"
        android:layout_marginTop="23dp"
        android:text="CLEAR"
        app:layout_constraintLeft_toRightOf="@+id/buttonConvert"
        app:layout_constraintTop_toBottomOf="@+id/spinnerTo"
        android:layout_marginStart="42dp" />

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="495dp"
        android:orientation="horizontal"
        android:layout_marginRight="8dp"
        android:background="#e40707"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginTop="30dp"
        app:layout_constraintTop_toBottomOf="@+id/buttonConvert"
        app:layout_constraintHorizontal_bias="0.0">

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="fill_parent"
            >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">

                <EditText
                    android:id="@+id/editText2"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:ems="10"
                    android:inputType="textPersonName"
                    android:text="Name" />

                <EditText
                    android:id="@+id/editText3"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:ems="10"
                    android:inputType="textPersonName"
                    android:text="Name" />

                <EditText
                    android:id="@+id/editText4"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:ems="10"
                    android:inputType="textPersonName"
                    android:text="Name" />

                <EditText
                    android:id="@+id/editText5"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:ems="10"
                    android:inputType="textPersonName"
                    android:text="Name" />

                <EditText
                    android:id="@+id/editText6"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:ems="10"
                    android:inputType="textPersonName"
                    android:text="Name" />

                <EditText
                    android:id="@+id/editText7"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:ems="10"
                    android:inputType="textPersonName"
                    android:text="Name" />

                <EditText
                    android:id="@+id/editText8"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:ems="10"
                    android:inputType="textPersonName"
                    android:text="Name" />

                <EditText
                    android:id="@+id/editText9"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:ems="10"
                    android:inputType="textPersonName"
                    android:text="Name" />
            </LinearLayout>

        </ScrollView>
    </LinearLayout>

</android.support.constraint.ConstraintLayout>

Body:
try this make your scroll view android:fillViewport="true"

<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">

 <LinearLayout
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:orientation="vertical">
  // add here all your controls
</LinearLayout>

</ScrollView>


问:
Powermock and Mockito - mock is ignored
I'm trying to inject a child mock to my Main.class, and it doesn't seem to work.
(Using powermock 1.7.0 with junit bundled with dependencies)

The verification says that my mocked object was not interacted. can't figure out why.

This is my Main.class:

```<code>public class Main {
  private Child child;

  public Main(){    }

  public void setChild(Child child){
    this.child = child;
  }

  public void play(){
    child = new Child();
    child.setNumber(50);
    System.out.println(child.getNumber());
  }
}
</code>```

This is my Child.class :

```<code>public class Child {

  private int number;

  public void setNumber(int number){
      this.number = number;
  }

  public int getNumber(){
      return number;
  }
}
</code>```

And this is my Test.class:

```<code>import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest({Child.class, Main.class})
public class MainTest {
    private Child child;
    private Main main;

    @Test
    public void testMain(){
        main = new Main();
        main.play();
        Mockito.verify(child).getNumber();
    }

    @Before
    public void setup(){
        child = mock(Child.class);
        when(child.getNumber()).thenReturn(10);
    }
}
</code>```

答:
The mock you create in your test is never actually used, because the Main object creates a new Child object each time you call play() on it.

What you want is a way to tell the production code to use the mocked child instance, e.g. by means of a setter.

Main

```<code>public void play(){
    // child = new Child(); // do not create a new instance each time
    child.setNumber(50);
    System.out.println(child.getNumber());
}
</code>```

MainTest

```<code>@Test
public void testMain(){
    main = new Main();
    main.setChild(child); // tell it to use the mock
    main.play();
    Mockito.verify(child).getNumber();
}
</code>```

Title: Powermock and Mockito - mock is ignored

Body:
I'm trying to inject a child mock to my Main.class, and it doesn't seem to work.
(Using powermock 1.7.0 with junit bundled with dependencies)

The verification says that my mocked object was not interacted. can't figure out why.

This is my Main.class:

public class Main {
  private Child child;

  public Main(){    }

  public void setChild(Child child){
    this.child = child;
  }

  public void play(){
    child = new Child();
    child.setNumber(50);
    System.out.println(child.getNumber());
  }
}

This is my Child.class :

public class Child {

  private int number;

  public void setNumber(int number){
      this.number = number;
  }

  public int getNumber(){
      return number;
  }
}

And this is my Test.class:

import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest({Child.class, Main.class})
public class MainTest {
    private Child child;
    private Main main;

    @Test
    public void testMain(){
        main = new Main();
        main.play();
        Mockito.verify(child).getNumber();
    }

    @Before
    public void setup(){
        child = mock(Child.class);
        when(child.getNumber()).thenReturn(10);
    }
}

Body:
The mock you create in your test is never actually used, because the Main object creates a new Child object each time you call play() on it.

What you want is a way to tell the production code to use the mocked child instance, e.g. by means of a setter.

Main

public void play(){
    // child = new Child(); // do not create a new instance each time
    child.setNumber(50);
    System.out.println(child.getNumber());
}

MainTest

@Test
public void testMain(){
    main = new Main();
    main.setChild(child); // tell it to use the mock
    main.play();
    Mockito.verify(child).getNumber();
}


问:
Unable to load provisioning/aws_driver when running chef test kitchen
I'm trying to set up kitchen and having difficulties with this aspect.

As far as I can tell, the yml looks correct but it's constantly error'ing when running the recipe.

The error:
LoadError

```<code>cannot load such file -- chef/provisioning/aws_driver
and
[2017-07-04T15:09:11+00:00] ERROR: cannot load such file -- chef/provisioning/aws_driver
[2017-07-04T15:09:11+00:00] ERROR: cannot load such file -- chef/provisioning/aws_driver
</code>```

my yml is:

```<code>driver:
name: ec2
aws_ssh_key_id: key
security_group_ids: ["sg-", "sg-"]
reqion: us-east-1
require_chef_omnibus: true
subnet_id: subnet-x
instance_type: t2.micro
associate_public_ip: true
interface: public

provisioner:
name: chef_zero

platforms:

name: amazon-linux
driver:
image_id: ami-a4c7edb2
transport:
ssh_key: C:\Keys.pem
connection_timeout: 10
connection_retries: 5
username: ec2-user
suites:

name: default
run_list:
recipe[solr::default]
attributes:
</code>```

答:
Resolved in comments, Test Kitchen normally installs the standard Chef installer package which does not include chef-provisioning. You can set it up to install and use ChefDK instead but this requires some complex configuration and currently has some major performance issues so it isn't recommended.

More directly in case people find this by Google, you can't (currently) use Test Kitchen to test chef-provisioning code as we have no systems in place to clean things up at the end of tests, nor is there a way to test anything about the systems that get created other than the Kitchen instance VM itself.

Body:
I'm trying to set up kitchen and having difficulties with this aspect.

As far as I can tell, the yml looks correct but it's constantly error'ing when running the recipe.

The error:
LoadError

cannot load such file -- chef/provisioning/aws_driver
and
[2017-07-04T15:09:11+00:00] ERROR: cannot load such file -- chef/provisioning/aws_driver
[2017-07-04T15:09:11+00:00] ERROR: cannot load such file -- chef/provisioning/aws_driver

my yml is:

driver:
name: ec2
aws_ssh_key_id: key
security_group_ids: ["sg-", "sg-"]
reqion: us-east-1
require_chef_omnibus: true
subnet_id: subnet-x
instance_type: t2.micro
associate_public_ip: true
interface: public

provisioner:
name: chef_zero

platforms:

name: amazon-linux
driver:
image_id: ami-a4c7edb2
transport:
ssh_key: C:\Keys.pem
connection_timeout: 10
connection_retries: 5
username: ec2-user
suites:

name: default
run_list:
recipe[solr::default]
attributes:


问:
jquery slider with variable width elements
is it possible to create a jquery slider in which the elements have variable width (i.e. not all elements have the same width) ?

If so, how do I do that ?
Hannit

答:
To set the width of a jQuery slider just wrap it in a div and style using CSS. You can also reference the child elements through CSS to style those as well, but that has to be done using jQuery after they have been rendered.

Example:

```<code><script type="text/javascript">
   $(document).ready(function(){
      //render the sliders
      $(".oSlider").slider({
         value: 12,
         min: 8,
         max: 24,
         step: 1
      });
      //size each handle according to class
      $(".narrow-handle .ui-slider-handle").css("width","10px");
      $(".wide-handle .ui-slider-handle").css("width","50px");
   });
</script>
<style type="text/css">
   /* define a width for the sliders by styling the wrapping div */
   .oSliderContainer { width:100px; }
   .oSliderContainer2 { width:200px; }
</style>

<div class="oSliderContainer"><div class="oSlider narrow-handle"></div></div>
<div class="oSliderContainer2"><div class="oSlider wide-handle"></div></div>
</code>```

I hope that answers your question, good luck!

OwnerDisplayName: hannit cohen

Body:
To set the width of a jQuery slider just wrap it in a div and style using CSS. You can also reference the child elements through CSS to style those as well, but that has to be done using jQuery after they have been rendered.

Example:

<script type="text/javascript">
   $(document).ready(function(){
      //render the sliders
      $(".oSlider").slider({
         value: 12,
         min: 8,
         max: 24,
         step: 1
      });
      //size each handle according to class
      $(".narrow-handle .ui-slider-handle").css("width","10px");
      $(".wide-handle .ui-slider-handle").css("width","50px");
   });
</script>
<style type="text/css">
   /* define a width for the sliders by styling the wrapping div */
   .oSliderContainer { width:100px; }
   .oSliderContainer2 { width:200px; }
</style>

<div class="oSliderContainer"><div class="oSlider narrow-handle"></div></div>
<div class="oSliderContainer2"><div class="oSlider wide-handle"></div></div>

I hope that answers your question, good luck!


问:
What is the quickest way to subtract a variable from a number and set the variable?
Is there a quicker way to do x = 128 - x?

答:
Short answer: No

If it was a division or multiplication by powers of 2, you could use bitwise shift operators to make it faster, but in this case, nothing is better than x = 128 - x


问:
How to format localised strings in Swift?
I am learning to localise my app to Simplified Chinese. I am following this tutorial on how to do this.

Because the tutorial is based on Obj-C, formatted strings can be written like this:

```<code>"Yesterday you sold %@ apps" = "Ayer le vendió %@ aplicaciones";
</code>```

"You like?" = "~Es bueno?~";

But I am using Swift. And in Swift I don't think you can use %@ to indicate that there is something to be placed there. We have string interpolation right?

My app is kind of related to maths. And I want to display which input(s) is used to compute the result in a detailed label of a table view cell. For example

```<code>--------------
1234.5678
From x, y <---- Here is the detailed label
--------------
</code>```

Here, From x, y means "The result is computed from x and y". I want to translate this to Chinese:

```<code>从 x, y 得出
</code>```

Before, I can just use this:

```<code>"From \(someVariable)"
</code>```

with the strings file:

```<code>"From" = "从 得出";
</code>```

And this is how I would use it in code

```<code>"\(NSLocalizedString("From", comment: "")) \(someVariable)"
</code>```

But if this were used in the Chinese version, the final string will be like this:

```<code>"从 得出 x, y"
</code>```

I mean I can put the 从 and 得出 in two different entries in the strings file. But is there a better way to do it?

答:
In objective C, if we want to get strings added at runtime as below

John Appleseed is the name

YourLocalizable.strings

```<code>"theStringToDisplay" = "%@ is the name";
</code>```

ViewController.m

```<code>NSString *username = @"John Appleseed";
NSString *messageBeforeFormat = NSLocalizedStringFromTable(@"theStringToDisplay", @"YourLocalizable", nil);
NSString *messageAfterFormat = [NSString stringWithFormat:messageBeforeFormat, username ];

self.yourLabel.text = messageAfterFormat;
</code>```

Further explanation in this nice post

https://www.oneskyapp.com/academy/learn-ios-localization/2-format-strings-plurals/

Body:
I am learning to localise my app to Simplified Chinese. I am following this tutorial on how to do this.

Because the tutorial is based on Obj-C, formatted strings can be written like this:

"Yesterday you sold %@ apps" = "Ayer le vendió %@ aplicaciones";

"You like?" = "~Es bueno?~";

But I am using Swift. And in Swift I don't think you can use %@ to indicate that there is something to be placed there. We have string interpolation right?

My app is kind of related to maths. And I want to display which input(s) is used to compute the result in a detailed label of a table view cell. For example

--------------
1234.5678
From x, y <---- Here is the detailed label
--------------

Here, From x, y means "The result is computed from x and y". I want to translate this to Chinese:

从 x, y 得出

Before, I can just use this:

"From \(someVariable)"

with the strings file:

"From" = "从 得出";

And this is how I would use it in code

"\(NSLocalizedString("From", comment: "")) \(someVariable)"

But if this were used in the Chinese version, the final string will be like this:

"从 得出 x, y"

I mean I can put the 从 and 得出 in two different entries in the strings file. But is there a better way to do it?

Body:
In objective C, if we want to get strings added at runtime as below

John Appleseed is the name

YourLocalizable.strings

"theStringToDisplay" = "%@ is the name";

ViewController.m

NSString *username = @"John Appleseed";
NSString *messageBeforeFormat = NSLocalizedStringFromTable(@"theStringToDisplay", @"YourLocalizable", nil);
NSString *messageAfterFormat = [NSString stringWithFormat:messageBeforeFormat, username ];

self.yourLabel.text = messageAfterFormat;

Further explanation in this nice post

https://www.oneskyapp.com/academy/learn-ios-localization/2-format-strings-plurals/


问:
Python round() too slow, faster way to reduce precision?
I am doing the following:

```<code>TOLERANCE = 13
some_float = ...
round(some_float, TOLERANCE)
</code>```

This is run many times, so performance is important. I have to round some_float due to floating point representation error. I don't actually need to "round" the number in that sense, just remove digits after 13 trailing digits.

Is there a faster way to do this?

答:
I've made some benches to compare round(some_float, TOLERANCE) with int(some_float * p + 0.5)/p (with p as 10**TOLERANCE) and here are the results:

round: 6.20 seconds

int divide+multiply: 3.53

my bench:

```<code>import time

TOLERANCE = 5
some_float = 12.2439924563634564564564
nb_loops = 10000000

start_time = time.time()
for _ in range(nb_loops):
    r1 = round(some_float, TOLERANCE)
print(r1,time.time()-start_time)

start_time = time.time()
p = float(10**TOLERANCE)
for _ in range(nb_loops):
    r2 = int(some_float * p + 0.5)/p
print(r2,time.time()-start_time)
</code>```

result:

```<code>12.24399 6.208600997924805
12.24399 3.525486946105957
</code>```

so the int solution is faster. round is probably better at handling the rounding of negative numbers (as someone commented, it makes a lot extra calls, so the code is more complex). The rounding may be different depending on the sign of the input number. Accuracy vs raw speed, again.

Add 0.5 or not to round or truncate. This seems to be a detail for you, but the int solution (provided that 10**TOLERANCE is precomputed) seems faster.

If you want to use that technique, you could be tempted to put the rounding code in a function:

```<code>TOLERANCE = 5
p = float(10**TOLERANCE)
def my_round_5(some_float):
    return int(some_float * p + 0.5)/p
</code>```

and call it like this:

```<code>r2 = my_round(some_float)
</code>```

that would be still faster than round, but a tad slower than using the formula inline (because function call isn't free)

note that I've used p = float(10**TOLERANCE) and not p = 10**TOLERANCE so the code is compatible with python 2 (else it would truncate the decimal part due to integer division)

Body:
I am doing the following:

TOLERANCE = 13
some_float = ...
round(some_float, TOLERANCE)

This is run many times, so performance is important. I have to round some_float due to floating point representation error. I don't actually need to "round" the number in that sense, just remove digits after 13 trailing digits.

Is there a faster way to do this?

Body:
I've made some benches to compare round(some_float, TOLERANCE) with int(some_float * p + 0.5)/p (with p as 10**TOLERANCE) and here are the results:

round: 6.20 seconds

int divide+multiply: 3.53

my bench:

import time

TOLERANCE = 5
some_float = 12.2439924563634564564564
nb_loops = 10000000

start_time = time.time()
for _ in range(nb_loops):
    r1 = round(some_float, TOLERANCE)
print(r1,time.time()-start_time)

start_time = time.time()
p = float(10**TOLERANCE)
for _ in range(nb_loops):
    r2 = int(some_float * p + 0.5)/p
print(r2,time.time()-start_time)

result:

12.24399 6.208600997924805
12.24399 3.525486946105957

so the int solution is faster. round is probably better at handling the rounding of negative numbers (as someone commented, it makes a lot extra calls, so the code is more complex). The rounding may be different depending on the sign of the input number. Accuracy vs raw speed, again.

Add 0.5 or not to round or truncate. This seems to be a detail for you, but the int solution (provided that 10**TOLERANCE is precomputed) seems faster.

If you want to use that technique, you could be tempted to put the rounding code in a function:

TOLERANCE = 5
p = float(10**TOLERANCE)
def my_round_5(some_float):
    return int(some_float * p + 0.5)/p

and call it like this:

r2 = my_round(some_float)

that would be still faster than round, but a tad slower than using the formula inline (because function call isn't free)

note that I've used p = float(10**TOLERANCE) and not p = 10**TOLERANCE so the code is compatible with python 2 (else it would truncate the decimal part due to integer division)

ContentLicense: CC BY-SA 4.0


问:
NOW() of SQL in Slick FRM
I am using Slick FRM to have it generate SQL code and connect to a MySQL server.

I failed to find a way to call NOW() function in SQL provided by MySQL server from within Scala code but have to generate a Datetime object and call its now() method in Scala code which results in obtaining the current time of the server that runs Scala application rather than the server time of the MySQL which would be obtained by calling NOW() in SQL code.

Can anyone shed some light ? Thanks.

答:
You are looking for User-Defined Features

In your case something like this should work:

```<code>val now = SimpleLiteral[java.sql.Date]("NOW")
</code>```

EDIT

According to GitHub issue it is not possible to use user defined functions in other use cases than queries. So it seems it is not a fit for your problem.

In that case I guess you have to use plain SQL for that one.

```<code>sqlu"""update TAoneBattSysRealtime set updateTime = NOW() where hwid = ${r.hwid}"""
</code>```

Title: NOW() of SQL in Slick FRM

Body:
You are looking for User-Defined Features

In your case something like this should work:

val now = SimpleLiteral[java.sql.Date]("NOW")

EDIT

According to GitHub issue it is not possible to use user defined functions in other use cases than queries. So it seems it is not a fit for your problem.

In that case I guess you have to use plain SQL for that one.

sqlu"""update TAoneBattSysRealtime set updateTime = NOW() where hwid = ${r.hwid}"""


问:
What are best practices for dealing with out of memory errors?
I'm wondering, what are good practices for dealing with out of memory errors.

```<code>void SomeTask()
{
   try
   {
      SomeObj obj = new SomeObj();
   }
   catch( std::bad_alloc& )
   {
      // What should be done here?
   }

   // ... more code ...
}
</code>```

I feel like silently returning is wrong because the program could be running in an indeterminate state. So, what should happen here, should I leave the program to crash, or is there a better alternative? This program runs as a service, so I can't just pop up an error message. I guess it might be possible to log something if there's enough memory left to do that. But, I'm just wondering, what do you think I should do in this kind of situation?

Thanks.

答:
Since it's a service, I would write an error to the system message log. In Windows, you can use the Windows Event Log API. Unless you've specified otherwise in your documentation, this is probably where a sysadmin will expect to see the failure report.

Also, in most C++ compilers, std::bad_alloc() has superseded a null return value for failed heap allocations.

-PaulH

Body:
I'm wondering, what are good practices for dealing with out of memory errors.

void SomeTask()
{
   try
   {
      SomeObj obj = new SomeObj();
   }
   catch( std::bad_alloc& )
   {
      // What should be done here?
   }

   // ... more code ...
}

I feel like silently returning is wrong because the program could be running in an indeterminate state. So, what should happen here, should I leave the program to crash, or is there a better alternative? This program runs as a service, so I can't just pop up an error message. I guess it might be possible to log something if there's enough memory left to do that. But, I'm just wondering, what do you think I should do in this kind of situation?

Thanks.


问:
DOM element behind previous one
I don't understand why my
{{ diff }}
 is not visible. It's behind my component and z-index doesn't help.

```<code><div class="chart">
  <div class="spent" :style="{ flex: flexSpent }"></div>
  <div class="remaining" :style="{ flex: flexRemaining }"></div>
</div>
<div class="text">{{ diff }}</div>
</code>```

The div .text is behind the div .chart, what am I doing wrong?

Demo

答:
To be able to use z-index, you must set position to absolute or relative.

CSS for your .text should be as follow:

```<code>.text {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100%;
        position:relative;
}
</code>```

Title: DOM element behind previous one

Body:
I don't understand why my
{{ diff }}
 is not visible. It's behind my component and z-index doesn't help.

{{ diff }}

The div .text is behind the div .chart, what am I doing wrong?

Demo

Body:
To be able to use z-index, you must set position to absolute or relative.

CSS for your .text should be as follow:

.text {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100%;
        position:relative;
}


问:
How to transfer blame from a deleted file to it's replacement?
I started with the file OldController.php and converted it to NewController.php. Here's my workflow:

Commit: Delete OldController.php and create NewController.php

Amend: Do some work on NewController.php

Amend: Do more work on NewController.php

(Pretty sure the amends hold no relevance, but figured I'd mention them anyways.)

So, how do I take the history of OldController.php and point it to NewController.php?

I know I can just go back and do this manually, but I'd like to know how to do this within mercurial.

答: Use hg cp (or hg mv if you only want to rename the file) instead of deleting one file and newly creating the other. That way mercurial knows that the new file is based on the old one and will display history accordingly


问:
FluentNHibernate Unidirectional One-To-Many Mapping
I have two classes. One is Order:

```<code>public class Order
{
    public virtual int Id { get; set; }
    public virtual IList<Product> Products { get; set; }
}
</code>```

The other one is Product:

```<code>public class Product
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
}
</code>```

They are fluently mapped like this:

```<code>public class OrderMap : ClassMap<Order>
{
    public OrderMap()
    {
        Table("Orders");
        Id(x => x.Id, "Id");
        HasMany(x => x.Products)
            .KeyColumn("OrderId")
            .Cascade.All();
    }
}

public class ProductMap : ClassMap<Product>
{
    public ProductMap()
    {
        Table("Products");
        Id(x => x.Id, "Id");
        Map(x => x.Name);
    }
}
</code>```

The database does NOT have a not-null constraint on the OrderId column of the Products table.
Problem is: both the order and the products are being persisted, however the products are being persisted with a null value on the OrderId column.

Am I missing something?

答: Well, as strange as it seems, we solved this issue here by re-working our Session management, using it to create an ITransaction in a using statement. Odd, but solved. Thanks everyone!</p>

Body:
I have two classes. One is Order:

public class Order
{
    public virtual int Id { get; set; }
    public virtual IList<Product> Products { get; set; }
}

The other one is Product:

public class Product
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
}

They are fluently mapped like this:

public class OrderMap : ClassMap<Order>
{
    public OrderMap()
    {
        Table("Orders");
        Id(x => x.Id, "Id");
        HasMany(x => x.Products)
            .KeyColumn("OrderId")
            .Cascade.All();
    }
}

public class ProductMap : ClassMap<Product>
{
    public ProductMap()
    {
        Table("Products");
        Id(x => x.Id, "Id");
        Map(x => x.Name);
    }
}

The database does NOT have a not-null constraint on the OrderId column of the Products table.
Problem is: both the order and the products are being persisted, however the products are being persisted with a null value on the OrderId column.

Am I missing something?


问:
Does Elasticsearch version 5.1.1 or later support the LIRE plugin?
Does Elasticsearch version 5.0 or later support the LIRE plugin?
If support LIRE plugin, how to install LIRE plugin?(in ubuntu)
I try to two way, and get error messages:

Running:

```<code>sudo bin/elasticsearch-plugin install com.github.kzwang/elasticsearch-image/1.2.0
</code>```

I've the error below:

```<code>ERROR: Unknown plugin com.github.kzwang/elasticsearch-image/1.2.0
</code>```

Running:

```<code>sudo bin/elasticsearch-plugin install https://github.com/kzwang/elasticsearch-image.git
</code>```

The error message is:

```<code>ERROR: 'elasticsearch' directory is missing in the plugin zip
</code>```

How do I install the plugin?

答:
Apparently this plugin has not been updated for 2.x and 5.x.

https://github.com/kzwang/elasticsearch-image/issues/19

IMO it would be better to rewrite this as an ingest plugin for elasticsearch. Would be a great addition IMO.

But to answer to your question, I don't think you can find an easy workaround for now.

Body:
Does Elasticsearch version 5.0 or later support the LIRE plugin?
If support LIRE plugin, how to install LIRE plugin?(in ubuntu)
I try to two way, and get error messages:

Running:

sudo bin/elasticsearch-plugin install com.github.kzwang/elasticsearch-image/1.2.0

I've the error below:

ERROR: Unknown plugin com.github.kzwang/elasticsearch-image/1.2.0

Running:

sudo bin/elasticsearch-plugin install https://github.com/kzwang/elasticsearch-image.git

The error message is:

ERROR: 'elasticsearch' directory is missing in the plugin zip

How do I install the plugin?


问:
Bad Request Your browser sent a request that this server could not understand
Although I am by no means an expert on Ubuntu, I have had two servers running for a couple of years with no problems.

Last night, when attempting to access a local website on one of them I got the error:

```<code>**Bad Request**
Your browser sent a request that this server could not understand.
Additionally, a 400 Bad Request error was encountered while trying to use an ErrorDocument to handle the request.
</code>```

After several hours of frustration and no success, I rebuilt the server.  While Ubuntu was installing I went to the other server and got the exact same error.
The first server has now been rebuilt and it displays the same error.

I have shut down every computer on the network.  Powered down the router and started over.

In addition to the two servers, the network consists of three windows machines and a Ubuntu desktop.

I have tried isolating the machines from the Internet, I have tried both wired and wireless clients.

Going to localhost on the servers displays the Ubuntu Apache Default page.

The only thing that happened about the time the problem started was the Windows decided to shutdown this machine for an update.  I don't see how this could have caused a problem but I have isolated this machine from the network and the problem exists.

I cleared cookies, used five different browsers, and they all report the same error. I'm about out of ideas, and looking for any suggestions.

答: In my case, it's actually the underscore _ in DocumentRoot that causes problem and hours of debugging. All work fine once I remove it from my DocumentRoot path.

Body:
Although I am by no means an expert on Ubuntu, I have had two servers running for a couple of years with no problems.

Last night, when attempting to access a local website on one of them I got the error:

**Bad Request**
Your browser sent a request that this server could not understand.
Additionally, a 400 Bad Request error was encountered while trying to use an ErrorDocument to handle the request.

After several hours of frustration and no success, I rebuilt the server.  While Ubuntu was installing I went to the other server and got the exact same error.
The first server has now been rebuilt and it displays the same error.

I have shut down every computer on the network.  Powered down the router and started over.

In addition to the two servers, the network consists of three windows machines and a Ubuntu desktop.

I have tried isolating the machines from the Internet, I have tried both wired and wireless clients.

Going to localhost on the servers displays the Ubuntu Apache Default page.

The only thing that happened about the time the problem started was the Windows decided to shutdown this machine for an update.  I don't see how this could have caused a problem but I have isolated this machine from the network and the problem exists.

I cleared cookies, used five different browsers, and they all report the same error. I'm about out of ideas, and looking for any suggestions.


问:
Why Android crashes instead of showing the error in debug mode
At first, my story:

So after a while, I have found the reason which causes the crashing of my app in debug mode!!
I used replace command to replace a fragment with another one, but it crashes and exits from debug mode. In the same sample, it works fine and finally, I got the problem that was about my forgetfulness about the implementation of its listener. Though, in the code, there was a throw command for unimplementation!

```<code>@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof OnFragmentInteractionListener) {
        mListener = (OnFragmentInteractionListener) context;
    } else {
        throw new RuntimeException(context.toString()
                + " must implement OnFragmentInteractionListener");
    }
}
</code>```

In Android Monitor when the crash happens, only these lines are appended:

07-05 08:05:54.797 6171-6171/com.shoniz.saledistributemobility

  D/AndroidRuntime: Shutting down VM

07-05 08:05:54.799    6171-6171/com.shoniz.saledistributemobility
  I/art: System.exit    called, status: 2

07-05 08:05:54.799    6171-6171/com.shoniz.saledistributemobility
  I/AndroidRuntime: VM    exiting with result code 2, cleanup skipped.

07-05 08:05:54.801    1303-1576/system_process D/GraphicsStats: Buffer
  count: 3

Now my question

Is there any way to force Android Studio to stop running and show the reason of the crash to save our time?! Something like a work that Visual Studio does.

答:
it crashes, because you throw an Exception, which then is not being handled with try / catch. the log which you've pasted is probably not "the interesting part" of it, at least cannot tell too much from it. added the "reflection" tag to the question, because that is what it is all about...

basically, there are two ways to get there:

```<code>if (! OnFragmentInteractionListener.class.isAssignableFrom(context)) {
    throw new ReflectiveOperationException(message);
}
</code>```

for testing purposes, it is more convenient to just log the error; as others suggested, those remote "Exceptions" are not necessarily real exceptions - one can log regular errors declared as a custom Exception to Firebase Crash Reporting and/or Crashlytics (with no force close in runtime, while not throwing anything).

```<code>if (! OnFragmentInteractionListener.class.isAssignableFrom(context)) {
    FirebaseCrash.report(new ReflectiveOperationException(message));
    if(BuildConfig.DEBUG) {Log.e(LOG_TAG, message);}
    return false;
}
</code>```

Body:
At first, my story:

So after a while, I have found the reason which causes the crashing of my app in debug mode!!
I used replace command to replace a fragment with another one, but it crashes and exits from debug mode. In the same sample, it works fine and finally, I got the problem that was about my forgetfulness about the implementation of its listener. Though, in the code, there was a throw command for unimplementation!

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof OnFragmentInteractionListener) {
        mListener = (OnFragmentInteractionListener) context;
    } else {
        throw new RuntimeException(context.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

In Android Monitor when the crash happens, only these lines are appended:

07-05 08:05:54.797 6171-6171/com.shoniz.saledistributemobility

  D/AndroidRuntime: Shutting down VM

07-05 08:05:54.799    6171-6171/com.shoniz.saledistributemobility
  I/art: System.exit    called, status: 2

07-05 08:05:54.799    6171-6171/com.shoniz.saledistributemobility
  I/AndroidRuntime: VM    exiting with result code 2, cleanup skipped.

07-05 08:05:54.801    1303-1576/system_process D/GraphicsStats: Buffer
  count: 3

Now my question

Is there any way to force Android Studio to stop running and show the reason of the crash to save our time?! Something like a work that Visual Studio does.

Body:
it crashes, because you throw an Exception, which then is not being handled with try / catch. the log which you've pasted is probably not "the interesting part" of it, at least cannot tell too much from it. added the "reflection" tag to the question, because that is what it is all about...

basically, there are two ways to get there:

if (! OnFragmentInteractionListener.class.isAssignableFrom(context)) {
    throw new ReflectiveOperationException(message);
}

for testing purposes, it is more convenient to just log the error; as others suggested, those remote "Exceptions" are not necessarily real exceptions - one can log regular errors declared as a custom Exception to Firebase Crash Reporting and/or Crashlytics (with no force close in runtime, while not throwing anything).

if (! OnFragmentInteractionListener.class.isAssignableFrom(context)) {
    FirebaseCrash.report(new ReflectiveOperationException(message));
    if(BuildConfig.DEBUG) {Log.e(LOG_TAG, message);}
    return false;
}


问:
SQL Update query is causing two rows in a trigger
I use SQL Server 2005 and have the below question:

On a table A, I have a trigger which tracks any insert/update/delete to it. The tracked records are inserted in an audit table (aAudit). When I run an update on A, I am seeing two rows in the audit table for each update, which is not what I expect. Here is the trigger that I have defined:

```<code>ALTER TRIGGER [ATrigger] ON [dbo].[A]
FOR INSERT, UPDATE, DELETE
AS
INSERT INTO [dbo].[aAudit]
([BusinessDate], [DataTypeId], [BookId], [Version], [DelFlag], [AuditDate], [ExtStatus])
SELECT [BusinessDate], [DataTypeId], [BookId], [Version], 'N', getDate(), 0
FROM inserted

INSERT INTO [dbo].[aAudit]
([BusinessDate], [DataTypeId], [BookId], [Version], [DelFlag], [AuditDate], [ExtStatus])
SELECT [BusinessDate], [DataTypeId], [BookId], [Version], 'Y', getDate(), 0
FROM deleted
</code>```

Why is the above trigger resulting in one row with DelFlag = 'Y' and one row with DelFalg = 'N' in the audit table?

Thanks for taking a look at my question.

Vikram

答:
In order to separate the three operations INSERT, UPDATE, DELETE, you need to do additional checks:</p>

```<code>ALTER TRIGGER [ATrigger] ON [dbo].[A]
FOR INSERT, UPDATE, DELETE
AS
   -- those are true INSERTs - the (ID) as primary key is *not* present in the "Deleted" table
   INSERT INTO [dbo].[aAudit]([BusinessDate], [DataTypeId], [BookId], [Version], [DelFlag], [AuditDate], [ExtStatus])
      SELECT [BusinessDate], [DataTypeId], [BookId], [Version], 'N', getDate(), 0
      FROM inserted
      WHERE (id) NOT IN (SELECT DISTINCT (id) FROM DELETED)

   -- those are true DELETEs - the (ID) as primary key is *not* present in the "Inserted" table
   INSERT INTO [dbo].[aAudit]([BusinessDate], [DataTypeId], [BookId], [Version], [DelFlag], [AuditDate], [ExtStatus])
      SELECT [BusinessDate], [DataTypeId], [BookId], [Version], 'Y', getDate(), 0
      FROM deleted
      WHERE (id) NOT IN (SELECT DISTINCT (id) FROM INSERTED)

   -- those are the UPDATEs - the (ID) as primary key is present in both the "Inserted" and "Deleted" table
   INSERT INTO [dbo].[aAudit]([BusinessDate], [DataTypeId], [BookId], [Version], [DelFlag], [AuditDate], [ExtStatus])
      SELECT [BusinessDate], [DataTypeId], [BookId], [Version], 'N', getDate(), 0
      FROM Inserted i
      INNER JOIN Deleted d on i.ID = d.ID
</code>```

Body:
I use SQL Server 2005 and have the below question:

On a table A, I have a trigger which tracks any insert/update/delete to it. The tracked records are inserted in an audit table (aAudit). When I run an update on A, I am seeing two rows in the audit table for each update, which is not what I expect. Here is the trigger that I have defined:

ALTER TRIGGER [ATrigger] ON [dbo].[A]
FOR INSERT, UPDATE, DELETE
AS
INSERT INTO [dbo].[aAudit]
([BusinessDate], [DataTypeId], [BookId], [Version], [DelFlag], [AuditDate], [ExtStatus])
SELECT [BusinessDate], [DataTypeId], [BookId], [Version], 'N', getDate(), 0
FROM inserted

INSERT INTO [dbo].[aAudit]
([BusinessDate], [DataTypeId], [BookId], [Version], [DelFlag], [AuditDate], [ExtStatus])
SELECT [BusinessDate], [DataTypeId], [BookId], [Version], 'Y', getDate(), 0
FROM deleted

Why is the above trigger resulting in one row with DelFlag = 'Y' and one row with DelFalg = 'N' in the audit table?

Thanks for taking a look at my question.

Vikram

Body:
In order to separate the three operations INSERT, UPDATE, DELETE, you need to do additional checks:

ALTER TRIGGER [ATrigger] ON [dbo].[A]
FOR INSERT, UPDATE, DELETE
AS
   -- those are true INSERTs - the (ID) as primary key is *not* present in the "Deleted" table
   INSERT INTO [dbo].[aAudit]([BusinessDate], [DataTypeId], [BookId], [Version], [DelFlag], [AuditDate], [ExtStatus])
      SELECT [BusinessDate], [DataTypeId], [BookId], [Version], 'N', getDate(), 0
      FROM inserted
      WHERE (id) NOT IN (SELECT DISTINCT (id) FROM DELETED)

   -- those are true DELETEs - the (ID) as primary key is *not* present in the "Inserted" table
   INSERT INTO [dbo].[aAudit]([BusinessDate], [DataTypeId], [BookId], [Version], [DelFlag], [AuditDate], [ExtStatus])
      SELECT [BusinessDate], [DataTypeId], [BookId], [Version], 'Y', getDate(), 0
      FROM deleted
      WHERE (id) NOT IN (SELECT DISTINCT (id) FROM INSERTED)

   -- those are the UPDATEs - the (ID) as primary key is present in both the "Inserted" and "Deleted" table
   INSERT INTO [dbo].[aAudit]([BusinessDate], [DataTypeId], [BookId], [Version], [DelFlag], [AuditDate], [ExtStatus])
      SELECT [BusinessDate], [DataTypeId], [BookId], [Version], 'N', getDate(), 0
      FROM Inserted i
      INNER JOIN Deleted d on i.ID = d.ID


问:
How to test POST web service call that send data in Custom Object?
I am using Retrofit for REST API calls. I want to check some APIs in Postman  but some Web service APIs send input data in Custom Object form.Unable to find how to test it in Postman or online .

Example :

```<code>@POST("/InsertBusinessInfo")
Call<Boolean> postBusinessInfo(@Body BusinessInfo businessRequest);
</code>```

This BusinessInfo pojo class with some params with get/set methods

```<code>public class BusinessInfo {

    public String getFirstName() {
        return FirstName;
    }

    public void setFirstName(String firstName) {
        FirstName = firstName;
    }

    public String getLastName() {
        return LastName;
    }

    public void setLastName(String lastName) {
        LastName = lastName;
    }
}
</code>```

How to test this in Postman. Is it the same as 1 by 1 params inserted in Body? Can anyone explain it?

答:
Yes it should be simple:

In postman add the POST endpoint (e.g. myBaseUrl/InsertBusinessInfo/)

Then with POST selected, in the Body select form encoding (e.g. x-www-form-urlencoded).

Now add your POJO field name as 'key' and your field value as 'value'.

This should then POST to your endpoint.

Body:
I am using Retrofit for REST API calls. I want to check some APIs in Postman  but some Web service APIs send input data in Custom Object form.Unable to find how to test it in Postman or online .

Example :

@POST("/InsertBusinessInfo")
Call<Boolean> postBusinessInfo(@Body BusinessInfo businessRequest);

This BusinessInfo pojo class with some params with get/set methods

public class BusinessInfo {

    public String getFirstName() {
        return FirstName;
    }

    public void setFirstName(String firstName) {
        FirstName = firstName;
    }

    public String getLastName() {
        return LastName;
    }

    public void setLastName(String lastName) {
        LastName = lastName;
    }
}

How to test this in Postman. Is it the same as 1 by 1 params inserted in Body? Can anyone explain it?


问:
How write automaticaly the name of the day in the name of a table?
I would like to know how to automatically write the name of the current  day in the table name when i execute a request like :

from qgpltemp.monday  (if i run on monday)

from qgpltemp.tuesday (if i run on tuesday)

etc...

(the table is already created with the good name before executing the request)

I have Tried :

```<code>select DAYNAME(CURRENT_DATE)as day,cast (row1 as integer) from qgpltemp.:day
</code>```

and some other things , but i often get the error :

```<code>Error: [SQL0104] Elément syntaxique : n'est pas correct. Eléments possibles : <IDENTIFIER>.
SQLState:  42601
ErrorCode: -104
</code>```

The command DAYNAME(CURRENT_DATE)as day works fine, i only get the name of the day if i manually write .monday etc...

答:
I think something like this could be what you're looking for

```<code>declare @day varchar(max)
select @day = datename(dw,getdate())

declare @sqlCommand varchar(max)
Select @sqlCommand = 'Select * from qgpltemp.' + @day

exec(@sqlCommand)
</code>```

if you insert that in your script it will execute the command to select all from a table called the current day.

Body:
I would like to know how to automatically write the name of the current  day in the table name when i execute a request like :

from qgpltemp.monday  (if i run on monday)

from qgpltemp.tuesday (if i run on tuesday)

etc...

(the table is already created with the good name before executing the request)

I have Tried :

select DAYNAME(CURRENT_DATE)as day,cast (row1 as integer) from qgpltemp.:day

and some other things , but i often get the error :

Error: [SQL0104] Elément syntaxique : n'est pas correct. Eléments possibles : <IDENTIFIER>.
SQLState:  42601
ErrorCode: -104

The command DAYNAME(CURRENT_DATE)as day works fine, i only get the name of the day if i manually write .monday etc...

Body:
I think something like this could be what you're looking for

declare @day varchar(max)
select @day = datename(dw,getdate())

declare @sqlCommand varchar(max)
Select @sqlCommand = 'Select * from qgpltemp.' + @day

exec(@sqlCommand)

if you insert that in your script it will execute the command to select all from a table called the current day.


问:
update values of auto_increment ID column on MySql using c#
I am new to MySql and coding. i have an Aid column that is Primary Key and Auto Increment in settings. But while I delete a row it doesn't update the Aid.

I know that the code that i need in MySql is :

```<code>SET @a = 0;
UPDATE aircraft.l1201 SET l1201.Aid = @a := @a +1;
</code>```

How can I translate this into c# code?

答:
I recommend you don't try changing the default behaviour of AutoIncrement. Changing all IDs after deleting a row doesn't bring you any real advantages, but a lot of disadvantages, including a potentially high amount of update operations after every delete as well as the risk of destroying referential integrity (in case ON UPDATE CASCADE isn't used).

Refer to this answer on a related question, it sums up the topic quite well.

Body:
I am new to MySql and coding. i have an Aid column that is Primary Key and Auto Increment in settings. But while I delete a row it doesn't update the Aid.

I know that the code that i need in MySql is :

SET @a = 0;
UPDATE aircraft.l1201 SET l1201.Aid = @a := @a +1;

How can I translate this into c# code?


问:
Parse a file for all occurrences of a string and generate key-values in JSON

I have a file (https://pastebin.com/STgtBRS8) in which I need to search for all the occurrences of the word "silencedetect".

I then have to generate a JSON file that contains the key-values of “silence_start”, “silence_end”, and “silence_duration”.

The JSON file should look like something like this:

```<code>[
{
"id": 1,
"silence_start": -0.012381,
"silence_end": 2.2059,
"silence_duration": 2.21828
},
{
"id": 2,
"silence_start": 5.79261,
"silence_end": 6.91955,
"silence_duration": 1.12694,
}
]
</code>```

This is what I have tried:

```<code>with open('volume_data.csv', 'r') as myfile:
    data = myfile.read().replace('\n', '')

for line in data:
    if "silencedetect" in data:
        #read silence_start, silence_end, and silence_duration and put in json
</code>```

I am unable to associate the 3 key-value pairs with each "silencedetect". How can I parse the key-values and get them in JSON format ?

答:
you can regex for it. it works for me on

```<code>import re

with open('volume_data.csv', 'r') as myfile:
    data = myfile.read()

d = re.findall('silence_start: (-?\d+\.\d+)\n.*?\n?\[silencedetect @ \w{14}\] silence_end: (-?\d+\.\d+) \| silence_duration: (-?\d+\.\d+)', data)
print d
</code>```

you could put them in a json by doing

```<code>out = [{'id': i, 'start':a[0], 'end':a[1], 'duration':a[2]} for i, a in enumerate(d)]
import json
print json.dumps(out) # or write to file or... whatever
</code>```

output:

```<code>'[{"duration": "2.21828", "start": "-0.012381", "end": "2.2059", "id": 0}, {"duration": "1.12694", "start": "5.79261", "end": "6.91955", "id": 1}, {"duration": "0.59288", "start": "8.53256", "end": "9.12544", "id": 2}, {"duration": "1.0805", "start": "9.64712", "end": "10.7276", "id": 3}, {"duration": "1.03406", "start": "12.6657", "end": "13.6998", "id": 4}, {"duration": "0.871519", "start": "19.2602", "end": "20.1317", "id": 5}'
</code>```

EDIT:
fixed fixed a bug that missed some matches because the frame=.. line fell between the start and end of the match

Body:
I have a file (https://pastebin.com/STgtBRS8) in which I need to search for all the occurrences of the word "silencedetect".

I then have to generate a JSON file that contains the key-values of “silence_start”, “silence_end”, and “silence_duration”.

The JSON file should look like something like this:

[
{
"id": 1,
"silence_start": -0.012381,
"silence_end": 2.2059,
"silence_duration": 2.21828
},
{
"id": 2,
"silence_start": 5.79261,
"silence_end": 6.91955,
"silence_duration": 1.12694,
}
]

This is what I have tried:

with open('volume_data.csv', 'r') as myfile:
    data = myfile.read().replace('\n', '')

for line in data:
    if "silencedetect" in data:
        #read silence_start, silence_end, and silence_duration and put in json

I am unable to associate the 3 key-value pairs with each "silencedetect". How can I parse the key-values and get them in JSON format ?

Body:
you can regex for it. it works for me on

import re

with open('volume_data.csv', 'r') as myfile:
    data = myfile.read()

d = re.findall('silence_start: (-?\d+\.\d+)\n.*?\n?\[silencedetect @ \w{14}\] silence_end: (-?\d+\.\d+) \| silence_duration: (-?\d+\.\d+)', data)
print d

you could put them in a json by doing

out = [{'id': i, 'start':a[0], 'end':a[1], 'duration':a[2]} for i, a in enumerate(d)]
import json
print json.dumps(out) # or write to file or... whatever

output:

'[{"duration": "2.21828", "start": "-0.012381", "end": "2.2059", "id": 0}, {"duration": "1.12694", "start": "5.79261", "end": "6.91955", "id": 1}, {"duration": "0.59288", "start": "8.53256", "end": "9.12544", "id": 2}, {"duration": "1.0805", "start": "9.64712", "end": "10.7276", "id": 3}, {"duration": "1.03406", "start": "12.6657", "end": "13.6998", "id": 4}, {"duration": "0.871519", "start": "19.2602", "end": "20.1317", "id": 5}'

EDIT:
fixed fixed a bug that missed some matches because the frame=.. line fell between the start and end of the match