问:
Unresolved reference: 'django' error in PyCharm
I'm trying to import:

```<code>from django.db import models
</code>```

PyCharm underlines django.db and complains: Unresolved reference 'django'.

How do I get PyCharm to recognize Django?

答:
I got this problem and it stopped my unit tests from running.

I found that PyCharm, during an upgrade, had set my Python Interpreter to one which was in a virtual environment, which I do not use any more for this project. So I set it to my global Python environment in C:\Python and everything works like a charm.

I hope this will help someone.

Body:
I'm trying to import:

from django.db import models

PyCharm underlines django.db and complains: Unresolved reference 'django'.

How do I get PyCharm to recognize Django?


来源: stackexchange

问:
PayPal IPN Unexpected Changes
Beginning sometime around 03/08/2017 we have noticed some unusual behavior with some (not all) of our PayPal IPNs. PayPal seems to be rolling out some kind of changes, there are a few others reporting other things, like: QueryString values removed from the IPN endpoint by PayPal

It looks like there are multiple versions of PayPal's system sending the IPNs, some of them contain notify_version=3.8 and some contain notify_version=UNVERSIONED.

The main problem is IPNs from "3.8" have receiver_email, but ones from "UNVERSIONED" do not.

In some cases we receive duplicate IPNs at the same time, one is the "3.8" version and one is the "UNVERSIONED" version. It seems like both versions of PayPal are handling the same thing at the same time. The "3.8" version seems to always successfully confirm the IPN and the "UNVERSIONED" version seems to always respond with "INVALID".

Some users are reporting that PayPal is unencoding the value we send for return (the URL that comes after the checkout). For example, a URL like http://example.com/some%3Dvalue sometimes gets decoded to http://example.com/some=value which is not correct and leads to a 404.

I am aware PayPal is set to roll out new changes on 03/29, relating to stricter compliance with their data formats, but we have already verified we are in compliance with this and this is still a few weeks away.

答: After a few days, IPNs returned to normal without any changes. PayPal never responded to our support emails or acknowledged any issue.</p>

ContentLicense: CC BY-SA 3.0

Title: PayPal IPN Unexpected Changes


问:
Wordpress: Disable part of Jquery function on mobile
I simply want to disable the below function on mobile. Here is a Pen. It works but when I resize my browser the hover effect doesn't work as desired ( hangs at the bottom of the h2 element. the desired effect is for the  to follow the mouse cursor).

jQuery

```<code>if ( jQuery(window).width() > 769) {
  jQuery(document).ready(function($){
      jQuery('.article__title').on('mouseenter mousemove', function(evt){
          jQuery(this).siblings('.article__img').css({left: evt.pageX+30, top: evt.pageY-200}).show();
          jQuery(this).on('mouseleave', function(){
              jQuery(this).siblings('.article__img').hide();
          });
      });
  });
}
</code>```

答:
If jQuery(window).width() > 769 is false then the code inside of it will never run. If it's true then it will. When you open the pen you'll most likely have a wide enough window. But that code runs once when the page loads and that's it. Resizing the window doesn't mean that code runs again, and even if it did you wouldn't want to call those functions multiple times.

What you need is to apply that condition inside jQuery('.article__title').on('mouseenter mousemove', function(evt){ so that it's checked every time you move the mouse.

Body:
I simply want to disable the below function on mobile. Here is a Pen. It works but when I resize my browser the hover effect doesn't work as desired ( hangs at the bottom of the h2 element. the desired effect is for the  to follow the mouse cursor).

jQuery

if ( jQuery(window).width() > 769) {
  jQuery(document).ready(function($){
      jQuery('.article__title').on('mouseenter mousemove', function(evt){
          jQuery(this).siblings('.article__img').css({left: evt.pageX+30, top: evt.pageY-200}).show();
          jQuery(this).on('mouseleave', function(){
              jQuery(this).siblings('.article__img').hide();
          });
      });
  });
}


问:
Sum of total sales values for a given year
In the following example I get the sum of sales per car with the following query:

```<code>id | cars
1    Ford
2    BMW
3    Fiat

id | id_cars | sales | sale_date
1       1        20      2016
2       1        30      2017
3       2        25      2017
4       2        35      2016
5       3        15      2017

SELECT car.id, car.cars, SUM(sal.sales) AS value_sales
FROM cars car
LEFT JOIN sales_cars sal  ON  car.id = sal.id_cars
GROUP BY car.id
</code>```

If I use the following segment in the query, I get only the registrations of cars that have sales in 2017, but that's not what I want.

```<code>AND YEAR(sal.sale_date) = YEAR(CURRENT_DATE())
</code>```

What I want to achieve is to get all records of cars sold (as in the previous query) but only the sum of the values of the current year.

For example : 1 | Ford | 30   and not 50 (2016 and 2017)

What is the correct way to do this query?

EDITED

Get current year and total years (following juergen answer):

```<code>SELECT car.id, car.cars,
   SUM(case when YEAR(sal.sale_date) = YEAR(CURRENT_DATE())
            then sal.sales
            else 0
       end) AS value_sales
   SUM(sal.sales) AS value_sales_total_years
FROM cars car
LEFT JOIN sales_cars sal  ON  car.id = sal.id_cars
GROUP BY car.id
</code>```

答:
Use a conditional SUM()</p>

```<code>SELECT car.id, car.cars,
       SUM(case when YEAR(sal.sale_date) = YEAR(CURRENT_DATE())
                then sal.sales
                else 0
           end) AS value_sales
FROM cars car
LEFT JOIN sales_cars sal  ON  car.id = sal.id_cars
GROUP BY car.id
</code>```

Body:
In the following example I get the sum of sales per car with the following query:

id | cars
1    Ford
2    BMW
3    Fiat

id | id_cars | sales | sale_date
1       1        20      2016
2       1        30      2017
3       2        25      2017
4       2        35      2016
5       3        15      2017

SELECT car.id, car.cars, SUM(sal.sales) AS value_sales
FROM cars car
LEFT JOIN sales_cars sal  ON  car.id = sal.id_cars
GROUP BY car.id

If I use the following segment in the query, I get only the registrations of cars that have sales in 2017, but that's not what I want.

AND YEAR(sal.sale_date) = YEAR(CURRENT_DATE())

What I want to achieve is to get all records of cars sold (as in the previous query) but only the sum of the values of the current year.

For example : 1 | Ford | 30   and not 50 (2016 and 2017)

What is the correct way to do this query?

EDITED

Get current year and total years (following juergen answer):

SELECT car.id, car.cars,
   SUM(case when YEAR(sal.sale_date) = YEAR(CURRENT_DATE())
            then sal.sales
            else 0
       end) AS value_sales
   SUM(sal.sales) AS value_sales_total_years
FROM cars car
LEFT JOIN sales_cars sal  ON  car.id = sal.id_cars
GROUP BY car.id

Body:
Use a conditional SUM()

SELECT car.id, car.cars,
       SUM(case when YEAR(sal.sale_date) = YEAR(CURRENT_DATE())
                then sal.sales
                else 0
           end) AS value_sales
FROM cars car
LEFT JOIN sales_cars sal  ON  car.id = sal.id_cars
GROUP BY car.id


问:
What is the proper way to iterate through a list with one item in python?
I have a list that only has one item. I know this list only has one item because it is the output of a MySQL query that will always have just one result.

MySQL Query:

```<code>SELECT MAX(date) FROM db.table;
</code>```

List result:

```<code>['20170307']
</code>```

Now I must access the item in this list. I have two options:

1) By position

```<code>max_date = list[0]
print(max_date)
</code>```

2) By iterating through item(s)

```<code>for item in list:
    max_date = item
print(max_date)
</code>```

Can someone please explain which approach is more appropriate in terms performance, readability, and overall best practice? My IDE raises a red flag when I use approach #2 but is it safe to ignore if I'm confident my list will always have one item?

答:
Access by index is very fast is most languages. You can also use the automatic unpacking in Python:</p>

```<code>try:
    first, = list_with_len_1
except ValueError:
    first = None
</code>```

Body:
I have a list that only has one item. I know this list only has one item because it is the output of a MySQL query that will always have just one result.

MySQL Query:

SELECT MAX(date) FROM db.table;

List result:

['20170307']

Now I must access the item in this list. I have two options:

1) By position

max_date = list[0]
print(max_date)

2) By iterating through item(s)

for item in list:
    max_date = item
print(max_date)

Can someone please explain which approach is more appropriate in terms performance, readability, and overall best practice? My IDE raises a red flag when I use approach #2 but is it safe to ignore if I'm confident my list will always have one item?

Body:
Access by index is very fast is most languages. You can also use the automatic unpacking in Python:

try:
    first, = list_with_len_1
except ValueError:
    first = None


问:
What is the best way to tell users of my library functions that passed variables are not of the correct type
I'm currently in the creation of a javascript function library. Mainly for my own use, but you can never be sure if someone else ends up using it in their projects, I'm atleast creating it as if that could happen.

Most methods only work if the variables that are passed are of the correct datatype. Now my question is: What is the best way to alert users that the variable is not of the correct type? Should one throw an error like this?

```<code>function foo(thisShouldBeAString){ //just pretend that this is a method and not a global function
 if(typeof(thisShouldBeAString) === 'string') {
  throw('foo(var), var should be of type string');
 }
 #yadayada
}
</code>```

I know that javascript does internal type conversion, but this can create very weird results (ie '234' + 5 = '2345' but '234' * 1 = 234) and this could make my methods do very weird things.

EDIT

To make things extra clear: I do not wish to do type conversion, the variables passed should be of the correct type. What is the best way to tell the user of my library that the passed variables are not of the correct type?

答:
You could check for some value like "debug=1" set. If there is - you could output errors like alerts. So in development mode user will see them, but on real site he will turn it off. Same way browser will not show you error message - you need to look at JS console.

Also there is FireBug. You could detect that and put FB debug Messages also.

OwnerDisplayName: Pim Jager

ContentLicense: CC BY-SA 2.5

Body:
I'm currently in the creation of a javascript function library. Mainly for my own use, but you can never be sure if someone else ends up using it in their projects, I'm atleast creating it as if that could happen.

Most methods only work if the variables that are passed are of the correct datatype. Now my question is: What is the best way to alert users that the variable is not of the correct type? Should one throw an error like this?

function foo(thisShouldBeAString){ //just pretend that this is a method and not a global function
 if(typeof(thisShouldBeAString) === 'string') {
  throw('foo(var), var should be of type string');
 }
 #yadayada
}

I know that javascript does internal type conversion, but this can create very weird results (ie '234' + 5 = '2345' but '234' * 1 = 234) and this could make my methods do very weird things.

EDIT

To make things extra clear: I do not wish to do type conversion, the variables passed should be of the correct type. What is the best way to tell the user of my library that the passed variables are not of the correct type?

LastEditorDisplayName: Mitch Wheat

OwnerDisplayName: Malx


问:
Appending JSON values to search results div
I'm attempting to append the results of a search query to a div, but getting the [object Object] result. How can I parse this this json object and retrieve/display only the title and permalink from the result?

json request

```<code>$("#searchterm").keyup(function(e) {
 var q = $("#searchterm").val();
 //Only begin search with at least 3 characters.
 if(q.length > 3){
    ajax_search();
 }
 //Send search query
 function ajax_search(){
 $.getJSON("http://url-to-search?q=" + q, {
          dataType:'jsonp'
   },
 //Get results and make 'em look good
 function(data) {
   console.log(data);
   $("#results").empty();
   $("#results").append("Results for <b> " + q + "</b>");
     $.each(data.query.search, function(i, data) {
         $("#results").append(data);
     });
  });
 }
});
</code>```

sample json

```<code>{
    "count": 50,
    "data": [{
        "id": "/folder/bob-jones/",
        "image": "https://image-url.jpg",
        "permalink": "/folder/bob-jones/",
        "text": "lots of text description here",
        "title": "Bob Jones",
        "type": "Employee"
    }]
}
</code>```

答:
EDIT:

As I don't have your URL to test this will be just a placeholder example:

```<code>$("#searchterm").keyup(function(e) {
 var q = $("#searchterm").val();
 //Only begin search with at least 3 characters.
 if(q.length > 3){
    ajax_search();
 }
 //Send search query
 function ajax_search(){
 $.getJSON("http://url-to-search?q=" + q, {
          dataType:'jsonp'
   },
 //Get results and make 'em look good
 function(data) {
   console.log(data);
   $("#results").empty();
   $("#results").append("Results for <b> " + q + "</b>");
     $.each(data.query.search, function(i, data) {
           alert(data.data[i].title);
     });
  });
 }
});
</code>```

Anyway, same concept as originally posted.

https://jsfiddle.net/2kcdhbmy/2/

Just created a JSFiddle for you:

```<code>var data = {
    "count": 50,
    "data": [{
        "id": "/folder/bob-jones/",
        "image": "https://image-url.jpg",
        "permalink": "/folder/bob-jones/",
        "text": "lots of text description here",
        "title": "Bob Jones",
        "type": "Employee"
    }]
}

alert(data.data[0].title);
</code>```

https://jsfiddle.net/2kcdhbmy/

Body:
I'm attempting to append the results of a search query to a div, but getting the [object Object] result. How can I parse this this json object and retrieve/display only the title and permalink from the result?

json request

$("#searchterm").keyup(function(e) {
 var q = $("#searchterm").val();
 //Only begin search with at least 3 characters.
 if(q.length > 3){
    ajax_search();
 }
 //Send search query
 function ajax_search(){
 $.getJSON("http://url-to-search?q=" + q, {
          dataType:'jsonp'
   },
 //Get results and make 'em look good
 function(data) {
   console.log(data);
   $("#results").empty();
   $("#results").append("Results for  " + q + "");
     $.each(data.query.search, function(i, data) {
         $("#results").append(data);
     });
  });
 }
});

sample json

{
    "count": 50,
    "data": [{
        "id": "/folder/bob-jones/",
        "image": "https://image-url.jpg",
        "permalink": "/folder/bob-jones/",
        "text": "lots of text description here",
        "title": "Bob Jones",
        "type": "Employee"
    }]
}

Body:
EDIT:

As I don't have your URL to test this will be just a placeholder example:

$("#searchterm").keyup(function(e) {
 var q = $("#searchterm").val();
 //Only begin search with at least 3 characters.
 if(q.length > 3){
    ajax_search();
 }
 //Send search query
 function ajax_search(){
 $.getJSON("http://url-to-search?q=" + q, {
          dataType:'jsonp'
   },
 //Get results and make 'em look good
 function(data) {
   console.log(data);
   $("#results").empty();
   $("#results").append("Results for <b> " + q + "</b>");
     $.each(data.query.search, function(i, data) {
           alert(data.data[i].title);
     });
  });
 }
});

Anyway, same concept as originally posted.

https://jsfiddle.net/2kcdhbmy/2/

Just created a JSFiddle for you:

var data = {
    "count": 50,
    "data": [{
        "id": "/folder/bob-jones/",
        "image": "https://image-url.jpg",
        "permalink": "/folder/bob-jones/",
        "text": "lots of text description here",
        "title": "Bob Jones",
        "type": "Employee"
    }]
}

alert(data.data[0].title);

https://jsfiddle.net/2kcdhbmy/


答:
You can shift the result by window-1 to get the left aligned results:

```<code>df["sum_value1"] = (df.groupby('Dimension').Value1
                      .apply(lambda x: x.rolling(window=3).sum().shift(-2)))
</code>```

Title: How to Reverse Rolling Sum?

Body:
I have a rolling sum calculated on a grouped data frame but its adding up the wrong way, it is a sum of the future, when I need a sum of the past.

What am I doing wrong here?

I import the data and sort by Dimension and Date (I have tried removing the date sort already)

df = pd.read_csv('Input.csv', parse_dates=True)
df.sort_values(['Dimension','Date'])
print(df)

I then create a new column which is a multi index grouped by rolling window

new_column = df.groupby('Dimension').Value1.apply(lambda x:
x.rolling(window=3).sum())

I then reset the index to be the same as the original

df['Sum_Value1'] = new_column.reset_index(level=0, drop=True)
print(df)

I have also tried reversing the index before the calculation, but that also failed.

Input

Dimension,Date,Value1,Value2
1,4/30/2002,10,20
1,1/31/2002,10,20
1,10/31/2001,10,20
1,7/31/2001,10,20
1,4/30/2001,10,20
1,1/31/2001,10,20
1,10/31/2000,10,20
2,4/30/2002,10,20
2,1/31/2002,10,20
2,10/31/2001,10,20
2,7/31/2001,10,20
2,4/30/2001,10,20
2,1/31/2001,10,20
2,10/31/2000,10,20
3,4/30/2002,10,20
3,1/31/2002,10,20
3,10/31/2001,10,20
3,7/31/2001,10,20
3,1/31/2001,10,20
3,10/31/2000,10,20

Output:

    Dimension        Date  Value1  Value2  Sum_Value1
0           1   4/30/2002      10      20         NaN
1           1   1/31/2002      10      20         NaN
2           1  10/31/2001      10      20        30.0
3           1   7/31/2001      10      20        30.0
4           1   4/30/2001      10      20        30.0
5           1   1/31/2001      10      20        30.0
6           1  10/31/2000      10      20        30.0
7           2   4/30/2002      10      20         NaN
8           2   1/31/2002      10      20         NaN
9           2  10/31/2001      10      20        30.0
10          2   7/31/2001      10      20        30.0
11          2   4/30/2001      10      20        30.0
12          2   1/31/2001      10      20        30.0
13          2  10/31/2000      10      20        30.0

Goal Output:

    Dimension        Date  Value1  Value2  Sum_Value1
0           1   4/30/2002      10      20        30.0
1           1   1/31/2002      10      20        30.0
2           1  10/31/2001      10      20        30.0
3           1   7/31/2001      10      20        30.0
4           1   4/30/2001      10      20        30.0
5           1   1/31/2001      10      20         NaN
6           1  10/31/2000      10      20         NaN
7           2   4/30/2002      10      20        30.0
8           2   1/31/2002      10      20        30.0
9           2  10/31/2001      10      20        30.0
10          2   7/31/2001      10      20        30.0
11          2   4/30/2001      10      20        30.0
12          2   1/31/2001      10      20         Nan
13          2  10/31/2000      10      20         NaN

Body:
You can shift the result by window-1 to get the left aligned results:

df["sum_value1"] = (df.groupby('Dimension').Value1
                      .apply(lambda x: x.rolling(window=3).sum().shift(-2)))


问:
How to change order of plots in pandas hist command
I'm trying to plot a set of histograms for a dataframe  with 25 columns named "Feature_1","Feature_2",...."Feature_25". When I use df.hist() it sorts individual histograms by their names so they are plotted in the following order: "Feature_1",""Feature_10","Feature_11"..."Feature_2","Feature_20",...
which is not what I need.

How do I change the sorting order? Passing columns parameter doesn't change anything.

I solved the problem by using matplotlib directly but that's not what I would prefer to do each time I need to plot several histograms.

答:
You could instead make repeated calls to hist with individual columns. Not sure if that fits all of your needs.

```<code>import pandas as pd

df = pd.DataFrame({'a':[1,1,1,1,3],
                  'b':[1,1,2,1,3],
                  'c':[2,2,2,1,3],
                  })

df[['c']].hist()
df[['a']].hist()
df[['b']].hist()
</code>```

Just iterate through the list of the columns in the order you would like

```<code>my_list = ['c','a','b']
for each in my_list:
    df[[each]].hist()
</code>```

Body:
You could instead make repeated calls to hist with individual columns. Not sure if that fits all of your needs.

import pandas as pd

df = pd.DataFrame({'a':[1,1,1,1,3],
                  'b':[1,1,2,1,3],
                  'c':[2,2,2,1,3],
                  })

df[['c']].hist()
df[['a']].hist()
df[['b']].hist()

Just iterate through the list of the columns in the order you would like

my_list = ['c','a','b']
for each in my_list:
    df[[each]].hist()


问:
how to click on a desktop icon (URL shortcut icon created in the desktop by the user) and open that?
i created a desktop icon (shortcut) for a URL (lets say a google.com shortcut on my desktop), so that when i click on it , IE opens and launches google.com website.  </p>

<p>is there anyway to program the second part ?
i am looking for the code to just click on that shortcut and somehow launch that page .
thanks   </p>

答:
```<code>Process.Start("cmd", @"/c %UserProfile%\Desktop\fileName.ext");
</code>```

This will open cmd.exe(command prompt) and pass the /c arguement to it followed by a command.  This essentially executes the command followed by /c.

Doing this will essentially do the same thing as double-clicking on the file.

Body:
i created a desktop icon (shortcut) for a URL (lets say a google.com shortcut on my desktop), so that when i click on it , IE opens and launches google.com website.

is there anyway to program the second part ?
i am looking for the code to just click on that shortcut and somehow launch that page .
thanks

Body:
Process.Start("cmd", @"/c %UserProfile%\Desktop\fileName.ext");

This will open cmd.exe(command prompt) and pass the /c arguement to it followed by a command.  This essentially executes the command followed by /c.

Doing this will essentially do the same thing as double-clicking on the file.


问:
Rails is not currently installed on this system yet I've already installed it
I'm going round in circles getting the "Rails is not installed on this system" message in Terminal, yet it tells me I've just installed it.

```<code>Simons-MacBook-Pro:~ Simon$ sudo gem install rails
Successfully installed rails-5.0.2
Parsing documentation for rails-5.0.2
Done installing documentation for rails after 0 seconds
1 gem installed
Simons-MacBook-Pro:~ Simon$ rails -v
Rails is not currently installed on this system. To get the latest version,
simply type:

$ sudo gem install rails

You can then rerun your "rails" command.
Simons-MacBook-Pro:~ Simon$
</code>```

Is there somewhere in particular I should be installing it?

答:
Solved it.  Found I had another copy in another path.  Deleted it and moved it into the same directory where I wanted to create the new app.

```<code>$sudo rails where
</code>```

allowed me to find it.

Body:
I'm going round in circles getting the "Rails is not installed on this system" message in Terminal, yet it tells me I've just installed it.

Simons-MacBook-Pro:~ Simon$ sudo gem install rails
Successfully installed rails-5.0.2
Parsing documentation for rails-5.0.2
Done installing documentation for rails after 0 seconds
1 gem installed
Simons-MacBook-Pro:~ Simon$ rails -v
Rails is not currently installed on this system. To get the latest version,
simply type:

$ sudo gem install rails

You can then rerun your "rails" command.
Simons-MacBook-Pro:~ Simon$

Is there somewhere in particular I should be installing it?

Body:
Solved it.  Found I had another copy in another path.  Deleted it and moved it into the same directory where I wanted to create the new app.

$sudo rails where

allowed me to find it.


问:
How to align input forms in HTML
I'm new to HTML and I'm trying to learn how to use forms.

The biggest issue I am having so far is aligning the forms. Here is an example of my current HTML file:

```<code><form>
 First Name:<input type="text" name="first"><br />
 Last Name:<input type="text" name="last"><br />
 Email:<input type="text" name="email"><br />
</form>
</code>```

The problem with this is, the field box after 'Email' is drastically different in terms of spacing compared to first, and last name. What is the 'proper' way to make it so that they 'line-up' essentially?

I am trying to practice good form and syntax...a lot of people might do this with CSS I am not sure, I have only learned the very basics of HTML so far.

答:
I'm a big fan of using definition lists.

They're easy to style using CSS, and they avoid the stigma of using tables for layout.

Username:

<input type="text" name="username" />

Password:

<input type="password" name="password" />

```

Title: How to align input forms in HTML

Body:
I'm new to HTML and I'm trying to learn how to use forms.

The biggest issue I am having so far is aligning the forms. Here is an example of my current HTML file:

<form>
 First Name:<input type="text" name="first">

 Last Name:<input type="text" name="last">

 Email:<input type="text" name="email">

</form>

The problem with this is, the field box after 'Email' is drastically different in terms of spacing compared to first, and last name. What is the 'proper' way to make it so that they 'line-up' essentially?

I am trying to practice good form and syntax...a lot of people might do this with CSS I am not sure, I have only learned the very basics of HTML so far.

Body:
I'm a big fan of using definition lists.

They're easy to style using CSS, and they avoid the stigma of using tables for layout.

<dl>
  <dt>Username:</dt>
  <dd><input type="text" name="username" /></dd>
  <dt>Password:</dt>
  <dd><input type="password" name="password" /></dd>
</dl>

ContentLicense: CC BY-SA 4.0


问:
Populate jTable from ArrayList<String>, without creating a new class.
I have a Web Service which returns ArrayList<String> from Database. I need to populate a jTable on client Java application with that ArrayList. How can I organise the ArrayList, so it shows in correct rows on the table? Currently it returns every element, separated with comma.

Here is the WebMethod bit:

```<code>@WebMethod(operationName = "ListCustomers")
public ArrayList ListCustomers() {
    try{
        Class.forName("org.apache.derby.jdbc.ClientDriver");
        Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/BankDB", "bankadmin", "bankadmin");
        Statement st = con.createStatement();
        PreparedStatement prst = con.prepareStatement("select Name, AccountNumber from CUSTOMERS");
        ArrayList<String> list = new ArrayList<>();
        ResultSet rs = prst.executeQuery();

        while(rs.next()){
            String nm = rs.getString("Name");
            String an = rs.getString("AccountNumber").toString();
            list.add(new String (nm));
            list.add(new String (an));
        }
        return (ArrayList) list;
    }
    catch(SQLException ex){
        System.err.println(ex.getMessage());
        return null;
    }
    catch (ClassNotFoundException ex) {
        Logger.getLogger(BankServerService.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println("second");
        return null;
    }
    finally{
        if(st != null){
            try {
                st.close();
            }
            catch(SQLException ex){
                System.out.println("Could not close statement");
            }
        }
    }
}
</code>```

This returns:

```<code>[TestName1, 46484654897, Name2, 646543543, emp3, 534354354]
</code>```

The client node looks like this, which I run in another method:

```<code>listCustomers();
        DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
        Object rowData[] = new Object[listCustomers().size()];
        for (int i=0; i<listCustomers().size(); i++){
            rowData[i] = listCustomers().get(i);
            model.addRow(rowData);
        }
</code>```

This populates only TestName1, 46484654897, into like 10 rows.

I need to show TestName1, Name2, emp3, on separate rows on 1st column of the table, and 46484654897, 646543543, 534354354 on separate rows on 2nd column.

答:
If your goal is to put each name/account number combination on it's own row, but you've got them all in a single list you would need to do something a bit different.

```<code>listCustomers();
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
for(int i = 0; i < listCustomers.size(); i+=2){
    Object[] rowdata = new Object[] {listCustomers.get(i), listCustomers.get(i+1)};

    model.addRow(rowdata);
}
</code>```

You increment i by 2 each time, since you only care about name + account number combo, and it goes in pairs.

Secondly you only want to pass model.addRow the object array with the data you want for that row. You were adding every string in listcustomer to it, then adding the whole array to the model as a row.

Above I just added a new rowdata object array inside the for loop, and populated it with the value at i (the name) and the value at i+1 (the account number). Keep in mind this will get out of sync if for some reason a name or account number is missing.

Body:
I have a Web Service which returns ArrayList<String> from Database. I need to populate a jTable on client Java application with that ArrayList. How can I organise the ArrayList, so it shows in correct rows on the table? Currently it returns every element, separated with comma.

Here is the WebMethod bit:

@WebMethod(operationName = "ListCustomers")
public ArrayList ListCustomers() {
    try{
        Class.forName("org.apache.derby.jdbc.ClientDriver");
        Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/BankDB", "bankadmin", "bankadmin");
        Statement st = con.createStatement();
        PreparedStatement prst = con.prepareStatement("select Name, AccountNumber from CUSTOMERS");
        ArrayList<String> list = new ArrayList<>();
        ResultSet rs = prst.executeQuery();

        while(rs.next()){
            String nm = rs.getString("Name");
            String an = rs.getString("AccountNumber").toString();
            list.add(new String (nm));
            list.add(new String (an));
        }
        return (ArrayList) list;
    }
    catch(SQLException ex){
        System.err.println(ex.getMessage());
        return null;
    }
    catch (ClassNotFoundException ex) {
        Logger.getLogger(BankServerService.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println("second");
        return null;
    }
    finally{
        if(st != null){
            try {
                st.close();
            }
            catch(SQLException ex){
                System.out.println("Could not close statement");
            }
        }
    }
}

This returns:

[TestName1, 46484654897, Name2, 646543543, emp3, 534354354]

The client node looks like this, which I run in another method:

listCustomers();
        DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
        Object rowData[] = new Object[listCustomers().size()];
        for (int i=0; i<listCustomers().size(); i++){
            rowData[i] = listCustomers().get(i);
            model.addRow(rowData);
        }

This populates only TestName1, 46484654897, into like 10 rows.

I need to show TestName1, Name2, emp3, on separate rows on 1st column of the table, and 46484654897, 646543543, 534354354 on separate rows on 2nd column.

Body:
If your goal is to put each name/account number combination on it's own row, but you've got them all in a single list you would need to do something a bit different.

listCustomers();
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
for(int i = 0; i < listCustomers.size(); i+=2){
    Object[] rowdata = new Object[] {listCustomers.get(i), listCustomers.get(i+1)};

    model.addRow(rowdata);
}

You increment i by 2 each time, since you only care about name + account number combo, and it goes in pairs.

Secondly you only want to pass model.addRow the object array with the data you want for that row. You were adding every string in listcustomer to it, then adding the whole array to the model as a row.

Above I just added a new rowdata object array inside the for loop, and populated it with the value at i (the name) and the value at i+1 (the account number). Keep in mind this will get out of sync if for some reason a name or account number is missing.


问:
Using Talend Open Studio DI to extract extract value from unique 1st row before continuing to process columns
I have a number of excel files where there is a line of text (and blank row) above the header row for the table.

What would be the best way to process the file so I can extract the text from that row AND include it as a column when appending multiple files? Is it possible without having to process each file twice?

Example

```<code>This file was created on machine A on 01/02/2013

Task|Quantity|ErrorRate

0102|4550|6 per minute
0103|4004|5 per minute
</code>```

And end up with the data from multiple similar files

```<code>Task|Quantity|ErrorRate|Machine|Date
0102|4550|6 per minute|machine A|01/02/2013
0103|4004|5 per minute|machine A|01/02/2013
0467|1264|2 per minute|machine D|02/02/2013
</code>```

答:
I put together a small, crude sample of how it can be done.  I call it crude because a. it is not dynamic,  you can add more files to process but you need to know how many files in advance of building your job, and b. it shows the basic concept, but would require more work to suite your needs. For example, in my test files I simply have "MachineA" or "MachineB" in the first line.  You will need to parse that data out to obtain the machine name and the date.

But here is how may sample works.  Each Excel is setup as two inputs.  For the header the tFileInput_Excel is configured to read only the first line while the body tFileInput_Excel is configured to start reading at line 4.

In the tMap they are combined (not joined) into the output schema.  This is done for the Machine A Excel and Machine B excels, then those tMaps are combined with a tUnite for the final output.

As you can see in the log row the data is combined and includes the header info.

Body:
I have a number of excel files where there is a line of text (and blank row) above the header row for the table.

What would be the best way to process the file so I can extract the text from that row AND include it as a column when appending multiple files? Is it possible without having to process each file twice?

Example

This file was created on machine A on 01/02/2013

Task|Quantity|ErrorRate

0102|4550|6 per minute
0103|4004|5 per minute

And end up with the data from multiple similar files

Task|Quantity|ErrorRate|Machine|Date
0102|4550|6 per minute|machine A|01/02/2013
0103|4004|5 per minute|machine A|01/02/2013
0467|1264|2 per minute|machine D|02/02/2013


问:
check if any duplicate words exist in a string using regex
Using regex in javascript, how to check for the condition when duplicate words are present in a string?
The words could be located any where in the string:

Given: "but boys run fast boys are strong" or

"boys boys"

expected result: true, since there are 2 repeats of the word "boys"

答:
Hello!

Here's an example with the exact answer you need:

```<code>var keyword = "boys"
var temp = "but boys run fast boys are strong";
var regex = new RegExp(keyword, "g");
var count = (temp.match(regex) || []).length;

if (count > 0) {
    console.log("true, since there are " + count + " repeats of the word '" + keyword + "'");
} else {
    console.log("false, not found.");
}
</code>```

I hope I have helped!

Body:
Hello!

Here's an example with the exact answer you need:

var keyword = "boys"
var temp = "but boys run fast boys are strong";
var regex = new RegExp(keyword, "g");
var count = (temp.match(regex) || []).length;

if (count > 0) {
    console.log("true, since there are " + count + " repeats of the word '" + keyword + "'");
} else {
    console.log("false, not found.");
}

I hope I have helped!


问:
Finding Android SDK on Mac and adding to PATH
I have installed Android Studio on my MacBook Air (OS Version 10.11 El Capitan) and have successfully written a small "hello, world" app and installed on device (Nexus 7) and ran on AVD.  All I want to do now is be able to build the app and install it on device from the command line as opposed to Android Studio.  I'm following the directions here:

http://developer.android.com/training/basics/firstapp/running-app.html

and the relevant line is:

Make sure the Android SDK platform-tools/ directory is included in your PATH environment variable, then execute:

The problem is I can't find the Android SDK on my machine!  I assume it's there because otherwise the program wouldn't compile and run through Android Studio?  Perhaps that's a bad assumption?  I'm new to Macs (I'm used to Windows) so I don't know the best way to search for the Android SDK.  So my questions:

How do I find Android SDK on my machine? Or prove to myself it's not there?

If it's not there how do I install it?

How do I change PATH to include Android SDK?

答:
If you don't want to open Android Studio just to modify your path...

They live here with a default installation:

```<code>${HOME}/Library/Android/sdk/tools
${HOME}/Library/Android/sdk/platform-tools
</code>```

Here's what you want to add to your .bashwhatever

```<code>export PATH="${HOME}/Library/Android/sdk/tools:${HOME}/Library/Android/sdk/platform-tools:${PATH}"
</code>```

Body:
If you don't want to open Android Studio just to modify your path...

They live here with a default installation:

${HOME}/Library/Android/sdk/tools
${HOME}/Library/Android/sdk/platform-tools

Here's what you want to add to your .bashwhatever

export PATH="${HOME}/Library/Android/sdk/tools:${HOME}/Library/Android/sdk/platform-tools:${PATH}"


问:
C macro and makefile and expressions not work as expected
In my C code, I need to check my kernel version and act according to it.
In the makefile I have the following:

```<code>KERNEL_MAJOR :=$(word 1, $(subst ., ,$(KERNEL_HEADERS)))
KERNEL_MINOR :=$(word 2, $(subst ., ,$(KERNEL_HEADERS)))
KERNEL_MICRO :=$(word 1, $(subst -, ,$(word 3, $(subst ., ,$(KERNEL_HEADERS)))))
KERNEL_PATCH_LEVEL :=$(word 1, $(subst ., ,$(word 2, $(subst -, ,$(KERNEL_HEADERS)))))
KARGS := KCPPFLAGS="-DKERNEL_MAJOR=$(KERNEL_MAJOR) -DKERNEL_MINOR=$(KERNEL_MINOR) -DKERNEL_MICRO=$(KERNEL_MICRO) -DKERNEL_PATCH_LEVEL=$(KERNEL_PATCH_LEVEL)"
</code>```

Samples:

3.0.101-0.47.71-default looks like:

```<code>KCPPFLAGS="-DKERNEL_MAJOR=3 -DKERNEL_MINOR=0 -DKERNEL_MICRO=101 -DKERNEL_PATCH_LEVEL=0"
</code>```

4.1.21.x86_64.1 (notice KERNEL_PATCH_LEVEL):

```<code>KCPPFLAGS="-DKERNEL_MAJOR=4 -DKERNEL_MINOR=1 -DKERNEL_MICRO=21 -DKERNEL_PATCH_LEVEL="
</code>```

I have macro in my code to check if kernel is 3.0.101.0 or 3.0.76.0:

```<code>#if defined(KERNEL_MAJOR) && defined(KERNEL_MINOR) && defined(KERNEL_MICRO) && defined(KERNEL_PATCH_LEVEL) && \
    (KERNEL_VERSION(KERNEL_MAJOR,KERNEL_MINOR,KERNEL_MICRO) == KERNEL_VERSION(3,0,101) || KERNEL_VERSION(KERNEL_MAJOR,KERNEL_MINOR,KERNEL_MICRO) == KERNEL_VERSION(3,0,76)) \
    && (KERNEL_PATCH_LEVEL == 0)
</code>```

There are 3 && boolean expressions, if expression #1 is ok, then i want to continue to expression #2, if expression #2 continue, i will continue to expression #3.
When i try to compile (make..) on kernel version 4.1.21.x86_64.1 i receive:

```<code>error: operator '==' has no left operand
</code>```

This is because -DKERNEL_PATCH_LEVEL="  - see the output.

I would expect the make to prevent me from getting to that && condition since expression #2 has failed (3.0.101 or 3.0.76)

答:
You are right in believing that the C preprocessor, like the C compiler,
performs short-circuit evaluation of &&- and ||-expressions.

But you are wrong in believing the preprocessor, unlike the compiler,
can perform "short-circuit" evaluation of nonsensical token sequences,
provided that the nonsense is in one of the contexts:

```<code>TRUE || [nonsense]
</code>```

or

```<code>FALSE && [nonsense]
</code>```

Just like the compiler, any sequence the preprocessor can evaluate as an
expression, short-circuiting or not, must be a (well-formed) expression,
which

```<code>FALSE && ( == 0)
</code>```

is not.

Body:
In my C code, I need to check my kernel version and act according to it.
In the makefile I have the following:

KERNEL_MAJOR :=$(word 1, $(subst ., ,$(KERNEL_HEADERS)))
KERNEL_MINOR :=$(word 2, $(subst ., ,$(KERNEL_HEADERS)))
KERNEL_MICRO :=$(word 1, $(subst -, ,$(word 3, $(subst ., ,$(KERNEL_HEADERS)))))
KERNEL_PATCH_LEVEL :=$(word 1, $(subst ., ,$(word 2, $(subst -, ,$(KERNEL_HEADERS)))))
KARGS := KCPPFLAGS="-DKERNEL_MAJOR=$(KERNEL_MAJOR) -DKERNEL_MINOR=$(KERNEL_MINOR) -DKERNEL_MICRO=$(KERNEL_MICRO) -DKERNEL_PATCH_LEVEL=$(KERNEL_PATCH_LEVEL)"

Samples:

3.0.101-0.47.71-default looks like:

KCPPFLAGS="-DKERNEL_MAJOR=3 -DKERNEL_MINOR=0 -DKERNEL_MICRO=101 -DKERNEL_PATCH_LEVEL=0"

4.1.21.x86_64.1 (notice KERNEL_PATCH_LEVEL):

KCPPFLAGS="-DKERNEL_MAJOR=4 -DKERNEL_MINOR=1 -DKERNEL_MICRO=21 -DKERNEL_PATCH_LEVEL="

I have macro in my code to check if kernel is 3.0.101.0 or 3.0.76.0:

#if defined(KERNEL_MAJOR) && defined(KERNEL_MINOR) && defined(KERNEL_MICRO) && defined(KERNEL_PATCH_LEVEL) && \
    (KERNEL_VERSION(KERNEL_MAJOR,KERNEL_MINOR,KERNEL_MICRO) == KERNEL_VERSION(3,0,101) || KERNEL_VERSION(KERNEL_MAJOR,KERNEL_MINOR,KERNEL_MICRO) == KERNEL_VERSION(3,0,76)) \
    && (KERNEL_PATCH_LEVEL == 0)

There are 3 && boolean expressions, if expression #1 is ok, then i want to continue to expression #2, if expression #2 continue, i will continue to expression #3.
When i try to compile (make..) on kernel version 4.1.21.x86_64.1 i receive:

error: operator '==' has no left operand

This is because -DKERNEL_PATCH_LEVEL="  - see the output.

I would expect the make to prevent me from getting to that && condition since expression #2 has failed (3.0.101 or 3.0.76)

Body:
You are right in believing that the C preprocessor, like the C compiler,
performs short-circuit evaluation of &&- and ||-expressions.

But you are wrong in believing the preprocessor, unlike the compiler,
can perform "short-circuit" evaluation of nonsensical token sequences,
provided that the nonsense is in one of the contexts:

TRUE || [nonsense]

or

FALSE && [nonsense]

Just like the compiler, any sequence the preprocessor can evaluate as an
expression, short-circuiting or not, must be a (well-formed) expression,
which

FALSE && ( == 0)

is not.


答:
You need a backward sum, therefore reverse your series before sum rolling it:</p>

```<code>lambda x: x[::-1].rolling(window=3).sum()
</code>```

Title: How to Reverse Rolling Sum?

Body:
You need a backward sum, therefore reverse your series before sum rolling it:

lambda x: x[::-1].rolling(window=3).sum()


问:
OWIN's GetExternalLoginInfoAsync Always Returns null
I've created a new MVC5 Web Application, and when I try to login with Google or Facebook, the ExternalLoginCallback Action in the AccountController is called, but GetExternalLoginInfoAsync() always returns null:

```<code>var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
if (loginInfo == null)
{
    return RedirectToAction("Login");
}
</code>```

Because it's always null, it just redirects back to the login page and the process starts over. How can I fix this?

答:
It seems that Nuget package Microsoft.Owin.Security.Facebook version 3.0.1 no longer works with Facebook Login.

Update this package to the pre-release 3.1.0 version, you can use the following:

Install-Package Microsoft.Owin.Security.Facebook -Pre

Body:
I've created a new MVC5 Web Application, and when I try to login with Google or Facebook, the ExternalLoginCallback Action in the AccountController is called, but GetExternalLoginInfoAsync() always returns null:

var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
if (loginInfo == null)
{
    return RedirectToAction("Login");
}

Because it's always null, it just redirects back to the login page and the process starts over. How can I fix this?


问:
LINQ is it possible to add where clauses dynamically
I want to search my db with different keys. According to the input, there may be 1 key to 10 keys. Is there a way to add OR/AND clauses to my Linq query dynamically?</p>

```<code> keys[k] // I have my keys in this array
 var feedList = (from feed in ctx.Feed
                 where feed.content.contains(keys[0])
                       && feed.content.contains(keys[1])
                       && ... // continues with the keys.length
                 select new {
                    FeedId = feed.DuyuruId,
                    FeedTitle = feed.FeedTitle,
                    FeedContent = feed.FeedContents,
                    FeedAuthor = user.UserName + " " +User.UserSurname
 }
</code>```

答:
I wanted to provide an example of how @mellamokb's answer worked for my scenario to possibly help out anyone needing a fairly dynamic linq query.

In my example I have simply made an extension of the datatable class so I can check if a row of data exists as it stands in the database so no SQL primary key exceptions are thrown.

```<code>/// <summary>
///
/// </summary>
/// <param name="DT"></param>
/// <param name="ColumnNames">Columns to check in affected table.</param>
/// <param name="ItemtoChecks">Values to check in affected column.</param>
/// <returns></returns>
public static bool TableContains(this DataTable DT, string[] ColumnNames, object[] ItemtoChecks)
{
  var result = from row in DT.AsEnumerable()
               where ColumnNames.All(
               r => row.Field<object>(r).ToString() == Convert.ToString(
                 ItemtoChecks[ColumnNames.ToList()
                 .FindIndex(p => p.Equals(r, StringComparison.OrdinalIgnoreCase))]))
               select row;
  return (result.Count() > 0);
}
</code>```

This method allows you to add as many column names as you require to a string[] along with the corresponding values to check in a separate object[]. The query checks against the datatable and if it finds a match the method returns true and if not it returns false.

Body:
I want to search my db with different keys. According to the input, there may be 1 key to 10 keys. Is there a way to add OR/AND clauses to my Linq query dynamically?

 keys[k] // I have my keys in this array
 var feedList = (from feed in ctx.Feed
                 where feed.content.contains(keys[0])
                       && feed.content.contains(keys[1])
                       && ... // continues with the keys.length
                 select new {
                    FeedId = feed.DuyuruId,
                    FeedTitle = feed.FeedTitle,
                    FeedContent = feed.FeedContents,
                    FeedAuthor = user.UserName + " " +User.UserSurname
 }

Body:
I wanted to provide an example of how @mellamokb's answer worked for my scenario to possibly help out anyone needing a fairly dynamic linq query.

In my example I have simply made an extension of the datatable class so I can check if a row of data exists as it stands in the database so no SQL primary key exceptions are thrown.

/// <summary>
///
/// </summary>
/// <param name="DT"></param>
/// <param name="ColumnNames">Columns to check in affected table.</param>
/// <param name="ItemtoChecks">Values to check in affected column.</param>
/// <returns></returns>
public static bool TableContains(this DataTable DT, string[] ColumnNames, object[] ItemtoChecks)
{
  var result = from row in DT.AsEnumerable()
               where ColumnNames.All(
               r => row.Field<object>(r).ToString() == Convert.ToString(
                 ItemtoChecks[ColumnNames.ToList()
                 .FindIndex(p => p.Equals(r, StringComparison.OrdinalIgnoreCase))]))
               select row;
  return (result.Count() > 0);
}

This method allows you to add as many column names as you require to a string[] along with the corresponding values to check in a separate object[]. The query checks against the datatable and if it finds a match the method returns true and if not it returns false.


问:
SQL Reduce Database rows - database size
I have a database that has sales of items by date, so in a given date there might be 800 rows for each item sold in the store. After a while, the table starts getting larger and larger, specially after some years. I can create an algorithm that will add the sales for a day, write a row with that data and instead of having 800 entries, I can have one entry instead.
Now, is there an easier way to do it with a SQL command. None of my books have a reference and I don't know if there is a command with a fancy name that I just don't know.

Kind Regards,

Daniel Hercules

答:
i had a similar problem, with more as 11 milion transaction for one store in one year. I solved this problem with 2 databases on sql server. First database is totally analiticlly database, with all transactions. Every night (after day closure process) i run a job, which groups by store and item (group by sales_date, store_number, item_id) and write into other database (with is "cumulative" database).
I hope this will help to to think in different direction... :)

Br, DaT


问:
How to return href of a class with javascript
Hello I can not figure this out. I am a noob with Javascriptbut I think this is the last piece of the puzzle I can't figure out.

```<code><div class="imgContainer DetailImage">                                                  <!-- Start extra info -->       <div id="p7IGM_1" class="p7IGM02 IGMnoscript">           <div class="p7IGM_wrapper">             <div
<div id="p7IGMimage_1"
class="p7IGM02_image"><a id="p7IGMimlink_1" class="p7IGM02-image-link viewImage"
rel="viewImage" href="https://www.mywebsite.com/ResourceFiles195/LGE/LargeImages/55LH5750_Primary.jpg"
title="55LH5750">
<img src= "/_resizeplugin/timthumb.php?src=https://www.mywebsite.com/ResourceFiles195/LGE/LargeImages/55LH5750_Primary.jpg&w=400&h=400&q=80"
</code>```

If this works to call img src;

```<code>function myFunc() {
  var img = document.querySelector(".imgContainer.DetailImage img");

  return img.src
}
</code>```

Why doesn’t this work at all to get the href? What am I doing wrong?

```<code>function myFunc() {
  var img = document.querySelector(".imgContainer.DetailImage href");

  return img
}
</code>```

答:
you can use</p>

```<code>document.querySelector(".imgContainer.DetailImage a").href
</code>```

Body:
Hello I can not figure this out. I am a noob with Javascriptbut I think this is the last piece of the puzzle I can't figure out.

             <div

<img src= "/_resizeplugin/timthumb.php?src=https://www.mywebsite.com/ResourceFiles195/LGE/LargeImages/55LH5750_Primary.jpg&w=400&h=400&q=80"

If this works to call img src;

function myFunc() {
  var img = document.querySelector(".imgContainer.DetailImage img");

  return img.src
}

Why doesn’t this work at all to get the href? What am I doing wrong?

function myFunc() {
  var img = document.querySelector(".imgContainer.DetailImage href");

  return img
}

Body:
you can use

document.querySelector(".imgContainer.DetailImage a").href


问:
When exactly is a Callable passed to an ExecutorService available for garbage collection
I have a thread pool of 8 and I am giving it approximately 100 instances of class implementing Callable i.e. WorkerThread

```<code>for (List<String> s : listOfLists) {
    Future<?> future = executor.submit(new Worker(hugeList));
}

for (Future<?> f : futures) {
        try {
            String result = (String) f.get();
        } catch (InterruptedException e) {
            logger.error("Interrupted", e);
        } catch (ExecutionException e) {
            logger.error("Execution exception", e);
        }
    }

            executor.shutdown();
</code>```

When will the instances passed to the executor be eligible for garbage collection? As soon as the f.get() is executed are they eligible for garbage collection or all the new Worker(hugeList) will remain in memory until the executor.shutdown() is called.

Every new Worker() is really big and I would them to be garbage collected after their respective thread is executed. But I am not sure when they are eligible for that.

答:
Unless the result of the callable references the callable itself, as soon as the task is executed, it's not referenced by anything, and thus becomes eligible to GC.

A pool is a queue where tasks wait to be executed, and a set of threads taking them out of the queue and executing them. Once executed, the pool doesn't care about the tasks anymore, and doesn't keep them anywhere.

Body:
I have a thread pool of 8 and I am giving it approximately 100 instances of class implementing Callable i.e. WorkerThread

for (List<String> s : listOfLists) {
    Future<?> future = executor.submit(new Worker(hugeList));
}

for (Future<?> f : futures) {
        try {
            String result = (String) f.get();
        } catch (InterruptedException e) {
            logger.error("Interrupted", e);
        } catch (ExecutionException e) {
            logger.error("Execution exception", e);
        }
    }

            executor.shutdown();

When will the instances passed to the executor be eligible for garbage collection? As soon as the f.get() is executed are they eligible for garbage collection or all the new Worker(hugeList) will remain in memory until the executor.shutdown() is called.

Every new Worker() is really big and I would them to be garbage collected after their respective thread is executed. But I am not sure when they are eligible for that.


问:
How to set AND expand variables in a heredoc section
I have a heredoc that needs to call existing variables from the main script, and set its own variables to use later. Something like this:

```<code>count=0

ssh $other_host <<ENDSSH
  if [[ "${count}" == "0" ]]; then
    output="string1"
  else
    output="string2"
  fi
  echo output
ENDSSH
</code>```

That doesn't work because 'output' doesn't get set to anything.

I tried using the solution from this question:

```<code>count=0

ssh $other_host << \ENDSSH
  if [[ "${count}" == "0" ]]; then
    output="string1"
  else
    output="string2"
  fi
  echo output
ENDSSH
</code>```

It didn't work either. $output got set to "string2" because $count wasn't expanded.

How can I use a heredoc that expands variables from the parent script, and sets its own variables?

答:
You can use:

```<code>count=0

ssh -t -t "$other_host" << ENDSSH
  if [[ "${count}" == "0" ]]; then
    output="string1"
  else
    output="string2"
  fi
  echo "\$output"
  exit
ENDSSH
</code>```

We use \$output so that it is expanded on remote host not locally.

Body:
I have a heredoc that needs to call existing variables from the main script, and set its own variables to use later. Something like this:

count=0

ssh $other_host <<ENDSSH
  if [[ "${count}" == "0" ]]; then
    output="string1"
  else
    output="string2"
  fi
  echo output
ENDSSH

That doesn't work because 'output' doesn't get set to anything.

I tried using the solution from this question:

count=0

ssh $other_host << \ENDSSH
  if [[ "${count}" == "0" ]]; then
    output="string1"
  else
    output="string2"
  fi
  echo output
ENDSSH

It didn't work either. $output got set to "string2" because $count wasn't expanded.

How can I use a heredoc that expands variables from the parent script, and sets its own variables?

Body:
You can use:

count=0

ssh -t -t "$other_host" << ENDSSH
  if [[ "${count}" == "0" ]]; then
    output="string1"
  else
    output="string2"
  fi
  echo "\$output"
  exit
ENDSSH

We use \$output so that it is expanded on remote host not locally.


问:
ASP.Net MVC vs. Ruby on Rails
If you were starting a new web development project would you use ASP.Net MVC 2 or Ruby on Rails?

I have recently invested some time in to learning Ruby on Rails because I wanted to learn a solid web development framework.  Then I took a new job where I will be using ASP.Net MVC 2.

I know this question is very subjective, but I am planning to write some websites on my own, outside of work, and I would like to get some opinions from others.

答:
Professionally, I'd go with what my team knows best (in my case, MVC and the .Net stack).  Since if you have a team with years of experience on a framework, a new app for a production system is not the place to learn new things.

Personally, I'd start by determining where I wanted to take my own learning plan next (I code in both Ruby and .Net, and have personal sites in MVC and Rails).  For example, when I wanted to do some personal development in BDD, Jquery, etc. I decided to do my site in MVC since I didn't want to add another learning opportunity at the same time.  Now, as I'm looking to build another learning site, I want to play with Cucumber, RSpec, and rails as a learning exercise (and build a nifty site to boot).

Lastly, if I was building a new site with the intent of selling a product or turning a profit, I would objectively figure out which I felt I could get out the door in a shippable state in the shortest time possible.  Today, that would be an MVC site.  Tomorrow, it might be Rails since I'm on a Ruby studying binge right now.

So to answer, I'd say it depends on your goals (business, learning, profit) and how this site fits either into your professional or entrepreneurial plans or your personal development plan.

Title: ASP.Net MVC vs. Ruby on Rails


问:
jQuery slide repeated code
I would like top know if there is a way to create several slides and panels using minimal code and avoid this:

```<code>$(document).ready(function(){
    $("#slide1").click(function(){
        $("#panel1").slideToggle("slow");
    });
    $("#slide2").click(function(){
        $("#panel2").slideToggle("slow");
    });
});
</code>```

As you can see, for every pair of panel and slide I have to create 3 new lines of jQuery. Is there a way to avoid this? I'm open to solutions that use Javascript as well. The goal of this is to simply have a few lines of code, and for every panel and slide involved, I don't have to add any code whatsoever. I simply have to add a slide and panel, and it will function.

答:
Including your HTML would be very important in this case. Depending on the relationship between your panels and slides, you may be able to make use of .siblings(), .parent(), children(), etc.

However, assuming they're not related at all and need to be selected by unique ID...

Give all your slides a common class:

```<code><div id="slide1" class="slide"></div>
<div id="slide2" class="slide"></div>
<div id="slide3" class="slide"></div>
</code>```

Put the handler on the common class instead of separate ID's, and get the "slide number", using $(this) to refer to the clicked slide. You can get the ID and remove the word "slide" from it, so all you're left with is the "slide number". Then, "#panel" + slideNumber should give you the associated panel.

```<code>$(".slide").click(function(){
    var slideNumber = $(this).attr("id").replace("slide","");
    $("#panel" + slideNumber).slideToggle("slow");
});
</code>```

As DaniP suggests in the comments below, if your slides are the only elements that begin with the word "slide", you could use a wildcard selector to match them by "ID starting with 'slide'", like so:

```<code>$([id=^"slide"]).click(function() { ... });
</code>```

You wouldn't need to implement the common class as I suggested earlier in this case.

Title: jQuery slide repeated code

Body:
I would like top know if there is a way to create several slides and panels using minimal code and avoid this:

$(document).ready(function(){
    $("#slide1").click(function(){
        $("#panel1").slideToggle("slow");
    });
    $("#slide2").click(function(){
        $("#panel2").slideToggle("slow");
    });
});

As you can see, for every pair of panel and slide I have to create 3 new lines of jQuery. Is there a way to avoid this? I'm open to solutions that use Javascript as well. The goal of this is to simply have a few lines of code, and for every panel and slide involved, I don't have to add any code whatsoever. I simply have to add a slide and panel, and it will function.

Body:
Including your HTML would be very important in this case. Depending on the relationship between your panels and slides, you may be able to make use of .siblings(), .parent(), children(), etc.

However, assuming they're not related at all and need to be selected by unique ID...

Give all your slides a common class:

<div id="slide1" class="slide"></div>
<div id="slide2" class="slide"></div>
<div id="slide3" class="slide"></div>

Put the handler on the common class instead of separate ID's, and get the "slide number", using $(this) to refer to the clicked slide. You can get the ID and remove the word "slide" from it, so all you're left with is the "slide number". Then, "#panel" + slideNumber should give you the associated panel.

$(".slide").click(function(){
    var slideNumber = $(this).attr("id").replace("slide","");
    $("#panel" + slideNumber).slideToggle("slow");
});

As DaniP suggests in the comments below, if your slides are the only elements that begin with the word "slide", you could use a wildcard selector to match them by "ID starting with 'slide'", like so:

$([id=^"slide"]).click(function() { ... });

You wouldn't need to implement the common class as I suggested earlier in this case.


问:
How to list object's array properties by sorted?
Each user has some professionals in array:

```<code>users  idxxx
           -A
           -prof: name: x
                  name: y
       idyyy
           -B
           -prof: name :y
                  name :z
                  name :x
</code>```

how to sort prof arrays lists by name order.

something like:

```<code>prof list:
x (2)
y (2)
z (1)
</code>```

答:
A better, alternative structure will alleviate the issue.

```<code>user_01
  -name: A
  -professors
     -YUik99j9s
         name: "prof name 0"
     -YJ89jk9sk
         name: "prof name 1"
</code>```

then read in the node

```<code>ref = "user_01/professors"
</code>```

and

```<code>orderBy:("name")
</code>```

Note that the professor child keys (-YUik99j9s and -YJ89jk9sk) are created with push() or childByAutoId depending on platform.

Body:
Each user has some professionals in array:

users  idxxx
           -A
           -prof: name: x
                  name: y
       idyyy
           -B
           -prof: name :y
                  name :z
                  name :x

how to sort prof arrays lists by name order.

something like:

prof list:
x (2)
y (2)
z (1)

Body:
A better, alternative structure will alleviate the issue.

user_01
  -name: A
  -professors
     -YUik99j9s
         name: "prof name 0"
     -YJ89jk9sk
         name: "prof name 1"

then read in the node

ref = "user_01/professors"

and

orderBy:("name")

Note that the professor child keys (-YUik99j9s and -YJ89jk9sk) are created with push() or childByAutoId depending on platform.


问:
Pass JavaScript Datetime zone to MVC controller without ActionResult View
I need one mvc controller without any View or Actions.
I need to use local browser zone
offset into varius of mvc controllers

if other browser - client enter
 to site,need to add his local zone
 and to use in all client only inctance

Do you thing that this way is correct regarding this feature?

This is my MVC controller. The first action not have any View and only set browser zone offset. The request call is from JS code.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;

namespace MvcApplication1.Controllers
{
    public class NoneViewController : Controller
    {
 //POST/NoneViewController/BrowserZoneOffset/-60
        [HttpPost]
        public void BrowserZoneOffset(int zone)
        {

              Requests.Headers.Add("time-zone-offset, zone);
        }

    [HttpGet]
    public ActionResult GetDateView()
     {

        // Here need to get inctance only data //from requests. If second browser open
// site need to get his zone
        int mydateOffset = Request.Headers["tume-zone"].FirstOrDefault();

        return new View(...);
     }

 }
</code>```

}

Here is my js where add local browser zone
This js call at the begging of web page home page

```<code> @section Scripts { < script type = "text/javascript" >
      //modify as needed to make it pass in what you need.
      function ZoneOffset(zoneId) {
       $.ajax({
         url: "/NoneViewController/BrowserZoneOffset/"+zoneId,
         // data: {zoneId: zoneId },
         cache: false,
         contentType: false,
         processData: false,
         type: "POST",
         success: function(data) {
          //TODO: Add whatever if you want to pass a notification back
         },
         error: function(error) {
          //TODO: Add some code here for error handling or notifications
         }
        }

// here set local browser zone offest
var dt = Datetime.Now(); var zoneOffset = dt.GetLocalZone();
ZoneOffset(zoneOffset);

< /script>
        }
</code>```

We can set uniq browser zone with that example

```<code>var localAspNetInctanceBrowser = Session.SessionID;

// int myLocalzone variable was set by
// JS.datetime.Now().getZoneOffset();

Session[localAspNetInctanceBrowser] = myLocalzone;
</code>```

答:
You can return Json(model) Then parse the result in your JavaScript code.

```<code>[HttpPost]
public ActionResult BrowserZoneOffset(int tz)
{
    PersistentStoreTimeZone(tz);

    return Json(new { status = "success" });
}
</code>```

Though, I don't think any of this is necessary if your datetime string format include the timezone offset.

Body:
I need one mvc controller without any View or Actions.
I need to use local browser zone
offset into varius of mvc controllers

if other browser - client enter
 to site,need to add his local zone
 and to use in all client only inctance

Do you thing that this way is correct regarding this feature?

This is my MVC controller. The first action not have any View and only set browser zone offset. The request call is from JS code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;

namespace MvcApplication1.Controllers
{
    public class NoneViewController : Controller
    {
 //POST/NoneViewController/BrowserZoneOffset/-60
        [HttpPost]
        public void BrowserZoneOffset(int zone)
        {

              Requests.Headers.Add("time-zone-offset, zone);
        }

    [HttpGet]
    public ActionResult GetDateView()
     {

        // Here need to get inctance only data //from requests. If second browser open
// site need to get his zone
        int mydateOffset = Request.Headers["tume-zone"].FirstOrDefault();

        return new View(...);
     }

 }

}

Here is my js where add local browser zone
This js call at the begging of web page home page

 @section Scripts { < script type = "text/javascript" >
      //modify as needed to make it pass in what you need.
      function ZoneOffset(zoneId) {
       $.ajax({
         url: "/NoneViewController/BrowserZoneOffset/"+zoneId,
         // data: {zoneId: zoneId },
         cache: false,
         contentType: false,
         processData: false,
         type: "POST",
         success: function(data) {
          //TODO: Add whatever if you want to pass a notification back
         },
         error: function(error) {
          //TODO: Add some code here for error handling or notifications
         }
        }

// here set local browser zone offest
var dt = Datetime.Now(); var zoneOffset = dt.GetLocalZone();
ZoneOffset(zoneOffset);

< /script>
        }

We can set uniq browser zone with that example

var localAspNetInctanceBrowser = Session.SessionID;

// int myLocalzone variable was set by
// JS.datetime.Now().getZoneOffset();

Session[localAspNetInctanceBrowser] = myLocalzone;

Body:
You can return Json(model) Then parse the result in your JavaScript code.

[HttpPost]
public ActionResult BrowserZoneOffset(int tz)
{
    PersistentStoreTimeZone(tz);

    return Json(new { status = "success" });
}

Though, I don't think any of this is necessary if your datetime string format include the timezone offset.


问:
decrypt random error with Laravel's built-in encryption facilities
I send invitation by mail to users with a encrypted email to know which user respond to invitation. Something like:

Hello, click on this link to start learning: https://example.org/start-learning?e=fwTreaN0WybffXdDfZZUNYB3FTFfZObCb7QFF5C4AFJvTjXabIPtRfcoXLkFYMUvD4FIZsmrDdEFN2OPKcTrAOSQLZfuKdfwcic1WtBxWSXWR1GEJD6we213A3BEPBpca0BxaaQ4GGMPFeRyXp6fPrG9WnTgWogwXUcnVtdwSEEdNHGuZsClTxR2AtD2JZN8VAEsRQKpFFShEDR2SET4KxGhLGM3M0FdDelrJtO8KXS2YRaddH==

The encrypted email is the long string above. I encode mail like this in a Mailable class:

```<code>$url = 'https://example.org/start-learning?e=' . encrypt($this->to[0]['address']);
</code>```

Then this $url is added in a mail template like this:

```<code><a href="{{$url}}>click me<a>
</code>```

Then, when user clicks the link, it routes to a controller and the controller decrypts the payload:

```<code>decrypt($request->input('e'));
</code>```

Then, it works for about 99% of people clicking link. But for about one percent, it does not work, I have an error decrypting. And I don't know why. This is the same Laravel application which encrypts and decrypts. Is there an reason for such a weird behavior?

Side note: I know decrypt always work and has not a random behavior (BTW I tested it on 10000 entries, it's OK). There must be something else with the mail process I don't understand.

答:
I think you should use urlencode() when creating link so instead of:

```<code>$url = 'https://example.org/start-learning?e=' . encrypt($this->to[0]['address']);
</code>```

you should use:

```<code>$url = 'https://example.org/start-learning?e=' . urlencode(encrypt($this->to[0]['address']));
</code>```

to make sure it will be valid.

Body:
I send invitation by mail to users with a encrypted email to know which user respond to invitation. Something like:

Hello, click on this link to start learning: https://example.org/start-learning?e=fwTreaN0WybffXdDfZZUNYB3FTFfZObCb7QFF5C4AFJvTjXabIPtRfcoXLkFYMUvD4FIZsmrDdEFN2OPKcTrAOSQLZfuKdfwcic1WtBxWSXWR1GEJD6we213A3BEPBpca0BxaaQ4GGMPFeRyXp6fPrG9WnTgWogwXUcnVtdwSEEdNHGuZsClTxR2AtD2JZN8VAEsRQKpFFShEDR2SET4KxGhLGM3M0FdDelrJtO8KXS2YRaddH==

The encrypted email is the long string above. I encode mail like this in a Mailable class:

$url = 'https://example.org/start-learning?e=' . encrypt($this->to[0]['address']);

Then this $url is added in a mail template like this:

click me

Then, when user clicks the link, it routes to a controller and the controller decrypts the payload:

decrypt($request->input('e'));

Then, it works for about 99% of people clicking link. But for about one percent, it does not work, I have an error decrypting. And I don't know why. This is the same Laravel application which encrypts and decrypts. Is there an reason for such a weird behavior?

Side note: I know decrypt always work and has not a random behavior (BTW I tested it on 10000 entries, it's OK). There must be something else with the mail process I don't understand.

Body:
I think you should use urlencode() when creating link so instead of:

$url = 'https://example.org/start-learning?e=' . encrypt($this->to[0]['address']);

you should use:

$url = 'https://example.org/start-learning?e=' . urlencode(encrypt($this->to[0]['address']));

to make sure it will be valid.


问:
python function for list of lists n long, with each element 0-m
I need to make a function so that I can put in two parameters, an order, and a max, and return a list of all of the lists 'order' long and with each element ranging from 0 to 'max'. I suspect I may need to use recursion, but I am getting lost in this.

so order = 2 max = 3 should return

```<code>[[0,0], [0,1], [0,2], [0,3], [1,0], [1,1], ... ,[3,3]]
</code>```

and order=4, max=5 should return

```<code>[[0,0,0,0], [0,0,0,1], [0,0,0,2], ...  [3,3,3,3]]
</code>```

Thanks for the help

答:
You don't need recursion; all you need is the Python itertools package:

```<code>import itertools
num_list = [x for x in range(max+1)]

for one_combo in itertools.combinations_with_replacement(num_list, order):
    ...
</code>```

Of course, you can combine the two computational lines; it's just easier to see this way.

Body:
I need to make a function so that I can put in two parameters, an order, and a max, and return a list of all of the lists 'order' long and with each element ranging from 0 to 'max'. I suspect I may need to use recursion, but I am getting lost in this.

so order = 2 max = 3 should return

[[0,0], [0,1], [0,2], [0,3], [1,0], [1,1], ... ,[3,3]]

and order=4, max=5 should return

[[0,0,0,0], [0,0,0,1], [0,0,0,2], ...  [3,3,3,3]]

Thanks for the help

Body:
You don't need recursion; all you need is the Python itertools package:

import itertools
num_list = [x for x in range(max+1)]

for one_combo in itertools.combinations_with_replacement(num_list, order):
    ...

Of course, you can combine the two computational lines; it's just easier to see this way.


问:
Cannot load the editActivity page
I am creating an application in Android studio that keeps track of the tv-shows that I've watched. However when I try to launch the EditShowActivity, by clicking on an item in my listview my phone app crashes. I can't figure out why or how.

Call to my EditShowActivity

```<code>listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Intent intent = new Intent(MainActivity.this, EditShowActivity.class);
                intent.putExtra(EXTRA_SHOW_ID, showArrayAdapter.getItem(position).getId());
                startActivityForResult(intent, 2);            }
        });
</code>```

This is my EditShowActivity

```<code>public class EditShowActivity extends AppCompatActivity {
    private Show show;
    private DataSource datasource;
    private EditText editText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit);

        datasource = new DataSource(this);
        long showId = getIntent().getLongExtra(MainActivity.EXTRA_SHOW_ID, -1);
        show = datasource.getShow(showId);

        TextView textView = (TextView) findViewById(R.id.details_textview);
        textView.setText(show.getShow());

        editText = (EditText) findViewById(R.id.details_updateText);

        Button updateButton = (Button) findViewById(R.id.details_updateButton);

        updateButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                show.setShows(editText.getText().toString());
                datasource.updateShow(show);
                Toast.makeText(EditShowActivity.this, "Assignment Updated", Toast.LENGTH_SHORT).show();

                Intent resultIntent = new Intent();
                setResult(Activity.RESULT_OK, resultIntent);
                finish();
            }

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

My activity_edit.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
    xmlns:fab="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.kevin.androidapp.EditShowActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"

            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_edit" />

</FrameLayout>
</code>```

My content_edit.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/activity_edit">

    <TextView
        android:id="@+id/details_textview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="44dp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:orientation="horizontal"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginBottom="10dp">

        <EditText
            android:id="@+id/details_updateText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1" />

        <Button
            android:id="@+id/details_updateButton"
            style="?android:attr/buttonStyleSmall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0"
            android:onClick="addListItem"
            android:text="Update" />

    </LinearLayout>

</RelativeLayout>
</code>```

答:
you could try:

```<code>intent.putExtra(MainActivity.EXTRA_SHOW_ID, (long) showArrayAdapter.getItem(position).getId());
</code>```

then:

```<code>long showId = (long) getIntent().getLongExtra(MainActivity.EXTRA_SHOW_ID, -1);
</code>```

Title: Cannot load the editActivity page

Body:
I am creating an application in Android studio that keeps track of the tv-shows that I've watched. However when I try to launch the EditShowActivity, by clicking on an item in my listview my phone app crashes. I can't figure out why or how.

Call to my EditShowActivity

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Intent intent = new Intent(MainActivity.this, EditShowActivity.class);
                intent.putExtra(EXTRA_SHOW_ID, showArrayAdapter.getItem(position).getId());
                startActivityForResult(intent, 2);            }
        });

This is my EditShowActivity

public class EditShowActivity extends AppCompatActivity {
    private Show show;
    private DataSource datasource;
    private EditText editText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit);

        datasource = new DataSource(this);
        long showId = getIntent().getLongExtra(MainActivity.EXTRA_SHOW_ID, -1);
        show = datasource.getShow(showId);

        TextView textView = (TextView) findViewById(R.id.details_textview);
        textView.setText(show.getShow());

        editText = (EditText) findViewById(R.id.details_updateText);

        Button updateButton = (Button) findViewById(R.id.details_updateButton);

        updateButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                show.setShows(editText.getText().toString());
                datasource.updateShow(show);
                Toast.makeText(EditShowActivity.this, "Assignment Updated", Toast.LENGTH_SHORT).show();

                Intent resultIntent = new Intent();
                setResult(Activity.RESULT_OK, resultIntent);
                finish();
            }

        });
    }
}

My activity_edit.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
    xmlns:fab="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.kevin.androidapp.EditShowActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"

            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_edit" />

</FrameLayout>

My content_edit.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/activity_edit">

    <TextView
        android:id="@+id/details_textview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="44dp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:orientation="horizontal"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginBottom="10dp">

        <EditText
            android:id="@+id/details_updateText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1" />

        <Button
            android:id="@+id/details_updateButton"
            style="?android:attr/buttonStyleSmall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0"
            android:onClick="addListItem"
            android:text="Update" />

    </LinearLayout>

</RelativeLayout>

Body:
you could try:

intent.putExtra(MainActivity.EXTRA_SHOW_ID, (long) showArrayAdapter.getItem(position).getId());

then:

long showId = (long) getIntent().getLongExtra(MainActivity.EXTRA_SHOW_ID, -1);


问:
How to stop reading from NetworkStream?
I'm trying to read data from NetworkStream. I write next code:

```<code>Imports System.Net
Imports System.Net.Sockets

Public Class Form1
    Dim tcpclnt1 As New TcpClient
    Dim streamTcp1 As NetworkStream
    Dim DataBuffer(1024) As Byte    'Buffer for reading
    Dim numberOfBytes As Integer
    ' event for reading data from stream
    Dim evtDataArrival As New AsyncCallback(AddressOf DataProcessing)

    Private Sub Btn_Connect5000_Click(sender As Object, e As EventArgs)_
            Handles Btn_Connect5000.Click
        ' Connecting to server
        tcpclnt1 = New TcpClient
        tcpclnt1.Connect("192.168.1.177", 5000)
        streamTcp1 = tcpclnt1.GetStream()   'Create stream for current tcpClient
        ' HERE WE START TO READ
        streamTcp1.BeginRead(DataBuffer, 0, DataBuffer.Length, evtDataArrival, Nothing)

    End Sub

    Public Sub DataProcessing(ByVal dr As IAsyncResult)
        numberOfBytes = streamTcp1.EndRead(dr) 'END READ
        ' ...HERE SOME ROUTINE FOR PRINT DATA TO TEXTBOXES...
        'START NEW READING
        streamTcp1.BeginRead(DataBuffer, 0, DataBuffer.Length, evtDataArrival, Nothing)
    End Sub

    Private Sub Btn_Disconnect5000_Click(sender As Object, e As EventArgs)_
            Handles Btn_Disconnect5000.Click
        ' Disconnect from port 5000. Close TcpClient
        streamTcp1.Dispose()
        streamTcp1.EndRead(Nothing) 'And here mistake appears !!!
        streamTcp1.Close()
        tcpclnt1.Close()
    End Sub
End Class
</code>```

Problem: I  create new client and new stream. By using BeginRead as I understand it starts to read data in new thread. So to do it for real time data, I start new BeginRead at the end of DataProcessing function. But I face the problem when try to disconnect (look at Btn_Disconnect5000_Click function): I try to close stream and client but it sill try to read in DataProcessing method and says me:

Cannot access a disposed object

(Thanks to djv for correct translation!).

So I suppose I need to stop thread first but can't figure out how to do this: I tried Dispose() method, tried close stream first but still can't. Also I tried to call EndRead method manually, but can't understand what I have to assign to it as argument (parameter).

答:
Just close the socket without call the EndRead.

At the moment that you are calling EndRead you are blocking the socket reading operation, as Microsoft's documentation says:

This method blocks until the I/O operation has completed.

Also you are calling the method Dispose, before the EndRead, which free all the resourses used by Stream and that is the reason that you have that exception.

Considere just close the socket, that will release all the resource that the socket is using, just like this:

```<code>Private Sub Btn_Disconnect5000_Click(sender As Object, e As EventArgs)_
    tcpclnt1.Close()
End Sub
</code>```

UPGRADE: Considere catch the exception of EndRead that is into the method DataProcessing. At the moment at you are closing the socket a System.ObjectDisposedException will be raise and the exception message is Cannot access a disposed object.. It happens because you are blocking the socket in EndRead and at the moment that tcpclnt1.Close() is invoked it unblocked and release all the resourses  of the socket (Disposed) and raise the exception.

So your DataProcessing should looks like:

```<code>Public Sub DataProcessing(ByVal dr As IAsyncResult)
    Try
        numberOfBytes = streamTcp1.EndRead(dr) 'END READ
        ' ...HERE SOME ROUTINE FOR PRINT DATA TO TEXTBOXES...
        'START NEW READING
        streamTcp1.BeginRead(DataBuffer, 0, DataBuffer.Length, evtDataArrival, Nothing)
    Catch ex As Exception
        System.Console.WriteLine(ex.Message)
    End Try

End Sub
</code>```

Title: How to stop reading from NetworkStream?

Body:
I'm trying to read data from NetworkStream. I write next code:

Imports System.Net
Imports System.Net.Sockets

Public Class Form1
    Dim tcpclnt1 As New TcpClient
    Dim streamTcp1 As NetworkStream
    Dim DataBuffer(1024) As Byte    'Buffer for reading
    Dim numberOfBytes As Integer
    ' event for reading data from stream
    Dim evtDataArrival As New AsyncCallback(AddressOf DataProcessing)

    Private Sub Btn_Connect5000_Click(sender As Object, e As EventArgs)_
            Handles Btn_Connect5000.Click
        ' Connecting to server
        tcpclnt1 = New TcpClient
        tcpclnt1.Connect("192.168.1.177", 5000)
        streamTcp1 = tcpclnt1.GetStream()   'Create stream for current tcpClient
        ' HERE WE START TO READ
        streamTcp1.BeginRead(DataBuffer, 0, DataBuffer.Length, evtDataArrival, Nothing)

    End Sub

    Public Sub DataProcessing(ByVal dr As IAsyncResult)
        numberOfBytes = streamTcp1.EndRead(dr) 'END READ
        ' ...HERE SOME ROUTINE FOR PRINT DATA TO TEXTBOXES...
        'START NEW READING
        streamTcp1.BeginRead(DataBuffer, 0, DataBuffer.Length, evtDataArrival, Nothing)
    End Sub

    Private Sub Btn_Disconnect5000_Click(sender As Object, e As EventArgs)_
            Handles Btn_Disconnect5000.Click
        ' Disconnect from port 5000. Close TcpClient
        streamTcp1.Dispose()
        streamTcp1.EndRead(Nothing) 'And here mistake appears !!!
        streamTcp1.Close()
        tcpclnt1.Close()
    End Sub
End Class

Problem: I  create new client and new stream. By using BeginRead as I understand it starts to read data in new thread. So to do it for real time data, I start new BeginRead at the end of DataProcessing function. But I face the problem when try to disconnect (look at Btn_Disconnect5000_Click function): I try to close stream and client but it sill try to read in DataProcessing method and says me:

Cannot access a disposed object

(Thanks to djv for correct translation!).

So I suppose I need to stop thread first but can't figure out how to do this: I tried Dispose() method, tried close stream first but still can't. Also I tried to call EndRead method manually, but can't understand what I have to assign to it as argument (parameter).

Body:
Just close the socket without call the EndRead.

At the moment that you are calling EndRead you are blocking the socket reading operation, as Microsoft's documentation says:

This method blocks until the I/O operation has completed.

Also you are calling the method Dispose, before the EndRead, which free all the resourses used by Stream and that is the reason that you have that exception.

Considere just close the socket, that will release all the resource that the socket is using, just like this:

Private Sub Btn_Disconnect5000_Click(sender As Object, e As EventArgs)_
    tcpclnt1.Close()
End Sub

UPGRADE: Considere catch the exception of EndRead that is into the method DataProcessing. At the moment at you are closing the socket a System.ObjectDisposedException will be raise and the exception message is Cannot access a disposed object.. It happens because you are blocking the socket in EndRead and at the moment that tcpclnt1.Close() is invoked it unblocked and release all the resourses  of the socket (Disposed) and raise the exception.

So your DataProcessing should looks like:

Public Sub DataProcessing(ByVal dr As IAsyncResult)
    Try
        numberOfBytes = streamTcp1.EndRead(dr) 'END READ
        ' ...HERE SOME ROUTINE FOR PRINT DATA TO TEXTBOXES...
        'START NEW READING
        streamTcp1.BeginRead(DataBuffer, 0, DataBuffer.Length, evtDataArrival, Nothing)
    Catch ex As Exception
        System.Console.WriteLine(ex.Message)
    End Try

End Sub


问:
Is it possible to switch between text views based on language?
I'm trying to find a way to switch between text views based on language, because some languages like hebrew and arabic are from right to left, so if I have two text views for example first text view says Park Name: and the second one says  Central park which sums it up to Park Name: Central Park, I need to reverse that to Central Park :Park Name, which concludes to just swapping their location, any idea how this could be done?</p>

答:
What is the layout?
If you use RelativeLayout, then you'll find

```<code>android:layout_alignParentStart="true" // for the Park Name
android:layout_alignParentEnd="true" // for the Central Park
</code>```

Thus will automatically swapping the location based on language

Body:
What is the layout?
If you use RelativeLayout, then you'll find

android:layout_alignParentStart="true" // for the Park Name
android:layout_alignParentEnd="true" // for the Central Park

Thus will automatically swapping the location based on language


问:
quick selection of a random row from a large table in mysql
What is a fast way to select a random row from a large mysql table?

I'm working in php, but I'm interested in any solution even if it's in another language.

答:
Create a Function to do this most likely the best answer and most fastest answer here!

Pros - Works even with Gaps and extremely fast.

```<code><?

$sqlConnect = mysqli_connect('localhost','username','password','database');

function rando($data,$find,$max = '0'){
   global $sqlConnect; // Set as mysqli connection variable, fetches variable outside of function set as GLOBAL
   if($data == 's1'){
     $query = mysqli_query($sqlConnect, "SELECT * FROM `yourtable` ORDER BY `id` DESC LIMIT {$find},1");

     $fetched_data = mysqli_fetch_assoc($query);
      if(mysqli_num_rows($fetched_data>0){
       return $fetch_$data;
      }else{
       rando('','',$max); // Start Over the results returned nothing
      }
   }else{
     if($max != '0'){
        $irand = rand(0,$max);
        rando('s1',$irand,$max); // Start rando with new random ID to fetch
     }else{

        $query = mysqli_query($sqlConnect, "SELECT `id` FROM `yourtable` ORDER BY `id` DESC LIMIT 0,1");
        $fetched_data = mysqli_fetch_assoc($query);
        $max = $fetched_data['id'];
        $irand = rand(1,$max);
        rando('s1',$irand,$max); // Runs rando against the random ID we have selected if data exist will return
     }
   }
 }

 $your_data = rando(); // Returns listing data for a random entry as a ASSOC ARRAY
?>
</code>```

Please keep in mind this code as not been tested but is a working concept to return random entries even with gaps.. As long as the gaps are not huge enough to cause a load time issue.

OwnerDisplayName: lajos

LastEditorDisplayName: lajos

Body:
Create a Function to do this most likely the best answer and most fastest answer here!

Pros - Works even with Gaps and extremely fast.

<?

$sqlConnect = mysqli_connect('localhost','username','password','database');

function rando($data,$find,$max = '0'){
   global $sqlConnect; // Set as mysqli connection variable, fetches variable outside of function set as GLOBAL
   if($data == 's1'){
     $query = mysqli_query($sqlConnect, "SELECT * FROM `yourtable` ORDER BY `id` DESC LIMIT {$find},1");

     $fetched_data = mysqli_fetch_assoc($query);
      if(mysqli_num_rows($fetched_data>0){
       return $fetch_$data;
      }else{
       rando('','',$max); // Start Over the results returned nothing
      }
   }else{
     if($max != '0'){
        $irand = rand(0,$max);
        rando('s1',$irand,$max); // Start rando with new random ID to fetch
     }else{

        $query = mysqli_query($sqlConnect, "SELECT `id` FROM `yourtable` ORDER BY `id` DESC LIMIT 0,1");
        $fetched_data = mysqli_fetch_assoc($query);
        $max = $fetched_data['id'];
        $irand = rand(1,$max);
        rando('s1',$irand,$max); // Runs rando against the random ID we have selected if data exist will return
     }
   }
 }

 $your_data = rando(); // Returns listing data for a random entry as a ASSOC ARRAY
?>

Please keep in mind this code as not been tested but is a working concept to return random entries even with gaps.. As long as the gaps are not huge enough to cause a load time issue.


问:
Moving mongo field within document if it exists
We are refactoring a mongo database, and I'd like to pull the value for one field, and place it into a hash in array in another field. Here is how the data looks in the document before:

```<code>basecampURL: "https://basecamp.com/123/",
trackingSystems: [
    {
        type: "github",
        url: "https://github.com/org/repo/issues/"
    }
]
</code>```

And here is what I'm hoping to accomplish:

```<code>trackingSystems: [
    {
        type: "basecamp",
        url: "https://basecamp.com/123/"
    },
    {
        type: "github",
        url: "https://github.com/org/repo/issues/"
    }
]
</code>```

I've tried a few variations of this code, and where I'm running into an issue is when referencing the found variable for basecampURL, all of the examples on MongoDB Update are using a string.

```<code>db.projects.update(
    { basecampURL: '.+' },
    { $push:
        { trackingSystems:
            {
                type: 'basecamp',
                url: basecampURL // this isn't valid, also tried $.basecampURL
            }
        },
      $unset:
        { basecampURL: '.+' }
    },
    { multi: true}
)
</code>```

It seems like I'm not finding how to reference the found item's properties, but I've been wondering if I need to do store the found variable prior to the update.

答:
Do not use a cursor if you can avoid it. They are extremely slow

Now there is mongo $rename:

db.COLLECTION_NAME.updateMany( {/*filter if you want*/}, { $rename: { "oldFieldName": "newFieldName" } } )

https://docs.mongodb.com/manual/reference/operator/update/rename/

Body:
We are refactoring a mongo database, and I'd like to pull the value for one field, and place it into a hash in array in another field. Here is how the data looks in the document before:

basecampURL: "https://basecamp.com/123/",
trackingSystems: [
    {
        type: "github",
        url: "https://github.com/org/repo/issues/"
    }
]

And here is what I'm hoping to accomplish:

trackingSystems: [
    {
        type: "basecamp",
        url: "https://basecamp.com/123/"
    },
    {
        type: "github",
        url: "https://github.com/org/repo/issues/"
    }
]

I've tried a few variations of this code, and where I'm running into an issue is when referencing the found variable for basecampURL, all of the examples on MongoDB Update are using a string.

db.projects.update(
    { basecampURL: '.+' },
    { $push:
        { trackingSystems:
            {
                type: 'basecamp',
                url: basecampURL // this isn't valid, also tried $.basecampURL
            }
        },
      $unset:
        { basecampURL: '.+' }
    },
    { multi: true}
)

It seems like I'm not finding how to reference the found item's properties, but I've been wondering if I need to do store the found variable prior to the update.