问:
How do i plot a pandas.DataFrame.plot.bar() with this weird columns in my pandas dataframe?
I currently have this dataframe that look like this:

Currently, i'm trying to plot a barplot that is grouped in such a way:

For each respective year_of_assessment, i want to plot the return_type, which shall be represented in 3 distinctive colors. And each year_of_assessment will be shown in the bar

However, i've tried to plot out the barchart and i ended out in this result:

Below is the code that i've tried to use to plot the bar plot:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# import the csv file
dataname = 'Datasets\\filing-of-tax-returns-for-individual-income-tax-and-corporate-income-tax.csv'
data = pd.read_csv(dataname,na_values=['na'])
df = pd.DataFrame(data)

# drop the NaN values
df2 = df.dropna()

# drop the rows that include values for individual income tax as it is irrelevent
df2 = df2[df2.tax_type != 'Individual Income Tax']
df2

# drop the column tax_type as we alr filter out to be a corporate income tax
df3 = df2.drop(columns = 'tax_type')
df3

# draw the bar chart to see the respectiive return_type for each respective year
df3.plot.bar(x='year_of_assessment',rot=0,figsize=(40,20))
plt.show()
```

Disclaimer: I was told not to use matplotlib to plot out the graph.

答:
You can plot this chart using Pandas' plot() by simply rearranging the data inside Pandas before you plot.

Simply pivot your data, so that the years of assessment becomes the index and the return types become the columns.

You can do that with the simple operation:

```<code>df4 = df3.pivot_table(
    index=['year_of_assessment'],
    columns=['return_type'],
)
</code>```

At this point, a simple df4.plot.bar() will do what you want.

You can make it slightly nicer by adjusting the labels of the axis, legend and title, but it's mostly cosmetic adjustments at this point:

```<code>ax = df4.plot.bar()
ax.legend(labels=df4.columns.levels[1])
ax.set_xlabel('Year of Assessment')
ax.set_title('Returns Received On Time')
plt.show()
</code>```

Here's a sample plot I got with a small sample of data that looks like the one you've shared:

Body:
I currently have this dataframe that look like this:

Currently, i'm trying to plot a barplot that is grouped in such a way:

For each respective year_of_assessment, i want to plot the return_type, which shall be represented in 3 distinctive colors. And each year_of_assessment will be shown in the bar

However, i've tried to plot out the barchart and i ended out in this result:

Below is the code that i've tried to use to plot the bar plot:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# import the csv file
dataname = 'Datasets\\filing-of-tax-returns-for-individual-income-tax-and-corporate-income-tax.csv'
data = pd.read_csv(dataname,na_values=['na'])
df = pd.DataFrame(data)

# drop the NaN values
df2 = df.dropna()

# drop the rows that include values for individual income tax as it is irrelevent
df2 = df2[df2.tax_type != 'Individual Income Tax']
df2

# drop the column tax_type as we alr filter out to be a corporate income tax
df3 = df2.drop(columns = 'tax_type')
df3

# draw the bar chart to see the respectiive return_type for each respective year
df3.plot.bar(x='year_of_assessment',rot=0,figsize=(40,20))
plt.show()

Disclaimer: I was told not to use matplotlib to plot out the graph.

Body:
You can plot this chart using Pandas' plot() by simply rearranging the data inside Pandas before you plot.

Simply pivot your data, so that the years of assessment becomes the index and the return types become the columns.

You can do that with the simple operation:

df4 = df3.pivot_table(
    index=['year_of_assessment'],
    columns=['return_type'],
)

At this point, a simple df4.plot.bar() will do what you want.

You can make it slightly nicer by adjusting the labels of the axis, legend and title, but it's mostly cosmetic adjustments at this point:

ax = df4.plot.bar()
ax.legend(labels=df4.columns.levels[1])
ax.set_xlabel('Year of Assessment')
ax.set_title('Returns Received On Time')
plt.show()

Here's a sample plot I got with a small sample of data that looks like the one you've shared:


来源: stackexchange

问:
Does BS4 offer a means to size `.input-group` down on various devices
I'm looking to size a BS4 input-group down as and when it is loaded on various devices. Kinda like how you can tell a col what it should be displaying on various screens. I.e.

I want to do something similar on mobile devices, I.e. on a desktop
  use .input-group-lg on a mobile use .input-group-sm etc.

Is this something BS4 can do? (I can't see any mention of it in the
  docs?)

Here's a jsfiddle with an example, if it helps.

答:
I just created two custom class for input-group resizing for small, medium and large screen.

1st for small+medium screen like .input-group-sm-md class.

2nd for small+medium+large screen like .input-group-sm-md-lg class.

I follow breakpoint of Bootstrap4.

Doc Link: https://getbootstrap.com/docs/4.4/layout/overview/#responsive-breakpoints

Note: check on Full page from snippet box and resize browser to check input-group resize reflection.

I hope below snippet will help you.

@media(min-width: 991px){
  /*Class for small + medium &large screen*/
  .input-group-sm-md-lg>.custom-select,
  .input-group-sm-md-lg>.form-control:not(textarea) {
    height: calc(1.5em + 1rem + 2px);
  }
  .input-group-sm-md-lg>.custom-select,
  .input-group-sm-md-lg>.form-control,
  .input-group-sm-md-lg>.input-group-append>.btn,
  .input-group-sm-md-lg>.input-group-append>.input-group-text,
  .input-group-sm-md-lg>.input-group-prepend>.btn,
  .input-group-sm-md-lg>.input-group-prepend>.input-group-text {
    padding: .5rem 1rem;
    font-size: 1.25rem;
    line-height: 1.5;
  }
}
@media(max-width: 575px){
  .input-group-sm-md-lg>.custom-select,
  .input-group-sm-md-lg>.form-control:not(textarea),
  .input-group-sm-md>.custom-select,
  .input-group-sm-md>.form-control:not(textarea){
    height: calc(1.5em + .5rem + 2px);
  }
  .input-group-sm-md-lg>.custom-select,
  .input-group-sm-md-lg>.form-control,
  .input-group-sm-md-lg>.input-group-append>.btn,
  .input-group-sm-md-lg>.input-group-append>.input-group-text,
  .input-group-sm-md-lg>.input-group-prepend>.btn,
  .input-group-sm-md-lg>.input-group-prepend>.input-group-text,
  /*Class small+medium screen*/
  .input-group-sm-md>.custom-select,
  .input-group-sm-md>.form-control,
  .input-group-sm-md>.input-group-append>.btn,
  .input-group-sm-md>.input-group-append>.input-group-text,
  .input-group-sm-md>.input-group-prepend>.btn,
  .input-group-sm-md>.input-group-prepend>.input-group-text{
    padding: .25rem .5rem;
    font-size: .875rem;
    line-height: 1.5;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

<div class="container my-3">
  <div class="row">
    <div class="col-sm-12">
      <form action="https://stackoverflow.com/users/7052927/raeesh-alam?tab=profile">
        <div class="input-group mb-3 input-group-sm-md">
          <input class="form-control" type="text" placeholder="input-group-sm-md">
          <span class="input-group-append">
            <button type="submit" class="btn btn-primary">Search</button>
          </span>
        </div>
        <div class="input-group mb-3 input-group-sm-md-lg">
          <input class="form-control" type="text" placeholder="input-group-sm-md-lg">
          <span class="input-group-append">
            <button type="submit" class="btn btn-primary">Search</button>
          </span>
        </div>
      </form>
    </div>
  </div>
</div></code>```

ContentLicense: CC BY-SA 4.0

Body:
I just created two custom class for input-group resizing for small, medium and large screen.

1st for small+medium screen like .input-group-sm-md class.

2nd for small+medium+large screen like .input-group-sm-md-lg class.

I follow breakpoint of Bootstrap4.

Doc Link: https://getbootstrap.com/docs/4.4/layout/overview/#responsive-breakpoints

Note: check on Full page from snippet box and resize browser to check input-group resize reflection.

I hope below snippet will help you.

@media(min-width: 991px){
  /*Class for small + medium &large screen*/
  .input-group-sm-md-lg>.custom-select,
  .input-group-sm-md-lg>.form-control:not(textarea) {
    height: calc(1.5em + 1rem + 2px);
  }
  .input-group-sm-md-lg>.custom-select,
  .input-group-sm-md-lg>.form-control,
  .input-group-sm-md-lg>.input-group-append>.btn,
  .input-group-sm-md-lg>.input-group-append>.input-group-text,
  .input-group-sm-md-lg>.input-group-prepend>.btn,
  .input-group-sm-md-lg>.input-group-prepend>.input-group-text {
    padding: .5rem 1rem;
    font-size: 1.25rem;
    line-height: 1.5;
  }
}
@media(max-width: 575px){
  .input-group-sm-md-lg>.custom-select,
  .input-group-sm-md-lg>.form-control:not(textarea),
  .input-group-sm-md>.custom-select,
  .input-group-sm-md>.form-control:not(textarea){
    height: calc(1.5em + .5rem + 2px);
  }
  .input-group-sm-md-lg>.custom-select,
  .input-group-sm-md-lg>.form-control,
  .input-group-sm-md-lg>.input-group-append>.btn,
  .input-group-sm-md-lg>.input-group-append>.input-group-text,
  .input-group-sm-md-lg>.input-group-prepend>.btn,
  .input-group-sm-md-lg>.input-group-prepend>.input-group-text,
  /*Class small+medium screen*/
  .input-group-sm-md>.custom-select,
  .input-group-sm-md>.form-control,
  .input-group-sm-md>.input-group-append>.btn,
  .input-group-sm-md>.input-group-append>.input-group-text,
  .input-group-sm-md>.input-group-prepend>.btn,
  .input-group-sm-md>.input-group-prepend>.input-group-text{
    padding: .25rem .5rem;
    font-size: .875rem;
    line-height: 1.5;
  }
}

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

<div class="container my-3">
  <div class="row">
    <div class="col-sm-12">
      <form action="https://stackoverflow.com/users/7052927/raeesh-alam?tab=profile">
        <div class="input-group mb-3 input-group-sm-md">
          <input class="form-control" type="text" placeholder="input-group-sm-md">
          <span class="input-group-append">
            <button type="submit" class="btn btn-primary">Search</button>
          </span>
        </div>
        <div class="input-group mb-3 input-group-sm-md-lg">
          <input class="form-control" type="text" placeholder="input-group-sm-md-lg">
          <span class="input-group-append">
            <button type="submit" class="btn btn-primary">Search</button>
          </span>
        </div>
      </form>
    </div>
  </div>
</div>


问:
Changing height of leading/trailingSwipeActions on a custom table cell
I'm currently developing a Swift 4 iOS application. I have a custom table cell that is displayed in a card view (see example screenshot below).

When I implement SwipeActions on a row, the height of the background color of the swipe menu takes up the full height of the cell row.

I'd like for it to be just the height of the card view. I should add that each row is a different height as they contain small pieces of text of varying length. Is there a way to achieve this?

答:
Exists an alternative to do this. You can change size, but it is old mode like change height (view.size.height= (newvalue)). To change position use (view.frame.origin.y = (newvalue)). It will work in static height cell and iOS >=11. This will not work in dynamic height cells. Make these changes inside the delegate method of tableviewcell

```<code> func tableView(_ tableView: UITableView, willBeginEditingRowAt indexPath: IndexPath) {

        if let cell = tableView.cellForRow(at: indexPath) as? TempcellTableViewCell{
            if let spvcell = cell.superview{
                for svswipe in spvcell.subviews{
                    let typeview = type(of: svswipe.self)
                    if typeview.description() == "UISwipeActionPullView"{
                        svswipe.frame.size.height = 100//size you want
                        svswipe.frame.origin.y = 5
                    }
                }
            }
        }
    }
</code>```

and in functions of leadingSwipeActionsConfigurationForRowAt/trailingSwipeActionsConfigurationForRowAt. Make following changes before it return UISwipeActionsConfiguration object.

```<code> func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let Cancel = UIContextualAction.init(style: .normal, title: "Cancel") { (action, view, nil) in
             print("Cancel")
         }
         Cancel.backgroundColor = UIColor.red

         let config = UISwipeActionsConfiguration.init(actions: [Cancel])
         config.performsFirstActionWithFullSwipe = false // Prevent swiping

         tableView.reloadRows(at: [indexPath], with: .none)

         return config
    }
</code>```

This solution worked for me :D ... I hope this answer can help you

ContentLicense: CC BY-SA 3.0

Body:
Exists an alternative to do this. You can change size, but it is old mode like change height (view.size.height= (newvalue)). To change position use (view.frame.origin.y = (newvalue)). It will work in static height cell and iOS >=11. This will not work in dynamic height cells. Make these changes inside the delegate method of tableviewcell

 func tableView(_ tableView: UITableView, willBeginEditingRowAt indexPath: IndexPath) {

        if let cell = tableView.cellForRow(at: indexPath) as? TempcellTableViewCell{
            if let spvcell = cell.superview{
                for svswipe in spvcell.subviews{
                    let typeview = type(of: svswipe.self)
                    if typeview.description() == "UISwipeActionPullView"{
                        svswipe.frame.size.height = 100//size you want
                        svswipe.frame.origin.y = 5
                    }
                }
            }
        }
    }

and in functions of leadingSwipeActionsConfigurationForRowAt/trailingSwipeActionsConfigurationForRowAt. Make following changes before it return UISwipeActionsConfiguration object.

 func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let Cancel = UIContextualAction.init(style: .normal, title: "Cancel") { (action, view, nil) in
             print("Cancel")
         }
         Cancel.backgroundColor = UIColor.red

         let config = UISwipeActionsConfiguration.init(actions: [Cancel])
         config.performsFirstActionWithFullSwipe = false // Prevent swiping

         tableView.reloadRows(at: [indexPath], with: .none)

         return config
    }

This solution worked for me :D ... I hope this answer can help you


问:
Why won't my local Apache open html pages?
so, I'm running Apache on my laptop.

If I go to "localhost", I get the page that says,

If you can see this, it means that the installation of the Apache web server software on this system was successful. You may now add content to this directory and replace this page.

except, I can't add content and replace that page.

I can click on its links, and that works fine.

First of all, there's not even an "index.html" document in that directory. If I try to directly access one that I created with localhost/index.html, I get "the request URL was not found on the server." So, I'm not even sure where that page is coming from. I've searched for words in that page under the apache directory, and nothing turns up. It seems to redirect somewhere.

Just as a test, I KNOW that it loads localhost/manual/index.html (doesn't matter what that is) so I tried to replace that with something I've written, and I received the message

The server encountered an internal error or misconfiguration and was unable to complete your request.

The error log says,

[Fri Sep 12 20:27:54 2008] [error] [client 127.0.0.1] Syntax error in type map, no ':' in C:/Program Files/Apache Group/Apache2/manual/index.html for header \r\n

But, that page works fine if I open directly with a browser.

so, basically, I don't know what I don't know here. I'm not sure what apache is looking for. I'm not sure if the error is in my config file, my html page, or what.

Oh, and the reason I want to open this using apache is (mainly) because I'm trying to test some php, so I'm trying to get apache to run locally.

Thanks.

答:
OK,

To answer my own. . .I found that the "Listen" directive in the configuration file had been set to "Listen 80" instead of "Listen localhost: 80".

Also, localhost/htdocs/index.html doesn't work, but localhost/index.html does.

Hopefully this can help someone in the future.

Thanks, Schroeder.

OwnerDisplayName: Baltimark

ContentLicense: CC BY-SA 2.5


问:
How can I select entries for a given weekday using SQL?
I could use this query to select all orders with a date on a monday:

```<code>SELECT * from orders WHERE strftime("%w", date)="1";
</code>```

But as far as I know, this can't be speed up using an index, as for every row strftime has to be calculated.

I could add an additional field with the weekday stored, but I want to avoid it. Is there a solution that makes use of an index or am I wrong and this query actually works fine? (That means it doesn't have to go through every row to calculate the result.)

答: Or as an alternative to vartec's suggestion, construct a calendar table consisting only of a date and a day name for each day in the year (both indexed) and then perform your query by doing a JOIN against this table.</p>

OwnerDisplayName: gs

Body:
I could use this query to select all orders with a date on a monday:

SELECT * from orders WHERE strftime("%w", date)="1";

But as far as I know, this can't be speed up using an index, as for every row strftime has to be calculated.

I could add an additional field with the weekday stored, but I want to avoid it. Is there a solution that makes use of an index or am I wrong and this query actually works fine? (That means it doesn't have to go through every row to calculate the result.)

OwnerDisplayName: anon


问:
jgGrid Search Dropdown Not Changing
This may be a followup to this question Possible to make jqGrid Search Box Stay on Page?  - Or it may be unrelated because clicking the search button manually shows the same behavior.

We have a dynamically generated grid that is created by a) making an ajax request to get the grid columns based on a report id and then b) setting up the grid model and fetching the data. When the page loads initially, we pass in a starting report id, but there is a dropdown box on the page that lets the user change reports.

When the dropdown changes, I unload any existing grid, make the ajax request to get the columns, set up the grid model, and then get the data.  The columns change, the data changes, and everything looks correct - except the search columns do not change in the search dropdown.

If I close the search box and reopen it, it still has the old search columns.  Likewise, if I click the reset button or reload the entire grid.

答:
I found it after a bit more poking around.  I needed to set the recreateFilter option to true </p>

```<code> prmSearch = {recreateFilter:true,multipleSearch:true,overlay:false,sopt:['cn','eq','ne','lt','le','gt','ge','in','ni','nc']};
</code>```

Title: jgGrid Search Dropdown Not Changing

Body:
I found it after a bit more poking around.  I needed to set the recreateFilter option to true

 prmSearch = {recreateFilter:true,multipleSearch:true,overlay:false,sopt:['cn','eq','ne','lt','le','gt','ge','in','ni','nc']};


问:
Need to group records based on matching reversal in sql
I have a tricky scenario to aggregate the data.

Data in my source table is as follows.

```<code>CustomerId  Transaction Type    Transaction Amount
1               Payment              100
1               ReversePayment      -100
1               payment              100
1               ReversePayment      -100
1               Payment              100
1               Payment              100
</code>```

Requirement is as follows:

If the payment as a assoociated Reversepayment with matched amount, sum these two records.

If the payment does not have an associated Reverse payment, consider it as orphan(dont sum it).

I want output to be like this.

```<code>  CustomerId    Transaction Type                Transaction Amount
   1                Payment,ReversePayment               0
   1                payment,ReversePayment               0
   1                payment                             100
   1               Payment                              100
</code>```

In this scenario,

First record which is payment has an associated reverse payment (2nd record), Hence the sum becomes 0

Third record which is payment has an associated reverse payment (4th record), then the sum becomes 0

Fifth and sixth does not have associated reversals. dont sum these records.

Second Example:

Data in the source as follows:

```<code> CustomerId Transaction Type    Transaction Amount
 1              Payment              100
 1              ReversePayment      -100
 1              payment              300
 1              ReversePayment      -300
 1               Payment              400
 1               Payment              500
</code>```

Expected Output

```<code>CustomerId      Transaction Type                Transaction Amount
 1              Payment,ReversePayment               0
 1              payment,ReversePayment               0
 1              payment                             400
 1              Payment                             500
</code>```

Second example requirement:
-As first and second records (payment and its associated reverse payment got
 matched) ,sum these two records, output is 0.
- As third and fourth records (payment and its associated reverse payment got
  matched), sum these two records, output is 0.
- Fifth and sixth does not have associated reversals. don't sum these records.

I got solutions in group, but data is not always guaranteed to have orphan records as 'payments'. Some times they are 'Payments' and some times they are 'ReversePayments'. Can some help me get ouptut like the below (using rank or rownumber functions ) so that i can group by using RRR column.

```<code>CustomerId  Transaction Type    Transaction Amount         RRR
 1              Payment              100                   1
 1              ReversePayment      -100                   1
 1              payment              100                   2
 1              ReversePayment      -100                   2
 1               Payment              100                   3
 1               Payment              100                   4

 CustomerId Transaction Type    Transaction Amount      RRR
 1              Payment              100                 1
 1              ReversePayment      -100                 1
 1              payment              300                 2
 1              ReversePayment      -300                 2
 1               Payment              400                3
 1               Payment              500                4
</code>```

答:
Edited to include your second scenario:

Using rownum to enforce inherent ordering (i.e. transactions happened in the order you've listed ), since your example is missing a transaction id or transaction time

```<code>    SQL> select * from trans_data2;

    CUSTOMER_ID TRANSACTION_TY TRANSACTION_AMOUNT
    ----------- -------------- ------------------
              1 Payment                       100
              1 ReversePayment               -100
              1 payment                       300
              1 ReversePayment               -300
              1 Payment                       400
              1 Payment                       500

    6 rows selected.

    SQL> select customer_id,
      2      case
      3          when upper(next_transaction) = 'REVERSEPAYMENT' then transaction_type||','||next_transaction
      4          else transaction_type
      5      end transaction_type,
      6      case
      7          when upper(next_transaction) = 'REVERSEPAYMENT' then transaction_amount + next_transaction_amount
      8          else transaction_amount
      9      end transaction_amount
     10  from (
     11      select customer_id, transaction_type, transaction_amount,
     12      lead (transaction_type) over ( partition by customer_id order by transaction_id ) next_transaction,
     13      nvl(lead (transaction_amount) over ( partition by customer_id order by transaction_id),0)  next_transaction_amount
     14      from ( select rownum transaction_id, t.* from trans_data2 t )
     15  ) where upper(transaction_type) = 'PAYMENT'
     16  ;

    CUSTOMER_ID TRANSACTION_TYPE              TRANSACTION_AMOUNT
    ----------- ----------------------------- ------------------
              1 Payment,ReversePayment                         0
              1 payment,ReversePayment                         0
              1 Payment                                      400
              1 Payment                                      500
</code>```

Body:
I have a tricky scenario to aggregate the data.

Data in my source table is as follows.

CustomerId  Transaction Type    Transaction Amount
1               Payment              100
1               ReversePayment      -100
1               payment              100
1               ReversePayment      -100
1               Payment              100
1               Payment              100

Requirement is as follows:

If the payment as a assoociated Reversepayment with matched amount, sum these two records.

If the payment does not have an associated Reverse payment, consider it as orphan(dont sum it).

I want output to be like this.

  CustomerId    Transaction Type                Transaction Amount
   1                Payment,ReversePayment               0
   1                payment,ReversePayment               0
   1                payment                             100
   1               Payment                              100

In this scenario,

First record which is payment has an associated reverse payment (2nd record), Hence the sum becomes 0

Third record which is payment has an associated reverse payment (4th record), then the sum becomes 0

Fifth and sixth does not have associated reversals. dont sum these records.

Second Example:

Data in the source as follows:

 CustomerId Transaction Type    Transaction Amount
 1              Payment              100
 1              ReversePayment      -100
 1              payment              300
 1              ReversePayment      -300
 1               Payment              400
 1               Payment              500

Expected Output

CustomerId      Transaction Type                Transaction Amount
 1              Payment,ReversePayment               0
 1              payment,ReversePayment               0
 1              payment                             400
 1              Payment                             500

Second example requirement:
-As first and second records (payment and its associated reverse payment got
 matched) ,sum these two records, output is 0.
- As third and fourth records (payment and its associated reverse payment got
  matched), sum these two records, output is 0.
- Fifth and sixth does not have associated reversals. don't sum these records.

I got solutions in group, but data is not always guaranteed to have orphan records as 'payments'. Some times they are 'Payments' and some times they are 'ReversePayments'. Can some help me get ouptut like the below (using rank or rownumber functions ) so that i can group by using RRR column.

CustomerId  Transaction Type    Transaction Amount         RRR
 1              Payment              100                   1
 1              ReversePayment      -100                   1
 1              payment              100                   2
 1              ReversePayment      -100                   2
 1               Payment              100                   3
 1               Payment              100                   4

 CustomerId Transaction Type    Transaction Amount      RRR
 1              Payment              100                 1
 1              ReversePayment      -100                 1
 1              payment              300                 2
 1              ReversePayment      -300                 2
 1               Payment              400                3
 1               Payment              500                4

Body:
Edited to include your second scenario:

Using rownum to enforce inherent ordering (i.e. transactions happened in the order you've listed ), since your example is missing a transaction id or transaction time

    SQL> select * from trans_data2;

    CUSTOMER_ID TRANSACTION_TY TRANSACTION_AMOUNT
    ----------- -------------- ------------------
              1 Payment                       100
              1 ReversePayment               -100
              1 payment                       300
              1 ReversePayment               -300
              1 Payment                       400
              1 Payment                       500

    6 rows selected.

    SQL> select customer_id,
      2      case
      3          when upper(next_transaction) = 'REVERSEPAYMENT' then transaction_type||','||next_transaction
      4          else transaction_type
      5      end transaction_type,
      6      case
      7          when upper(next_transaction) = 'REVERSEPAYMENT' then transaction_amount + next_transaction_amount
      8          else transaction_amount
      9      end transaction_amount
     10  from (
     11      select customer_id, transaction_type, transaction_amount,
     12      lead (transaction_type) over ( partition by customer_id order by transaction_id ) next_transaction,
     13      nvl(lead (transaction_amount) over ( partition by customer_id order by transaction_id),0)  next_transaction_amount
     14      from ( select rownum transaction_id, t.* from trans_data2 t )
     15  ) where upper(transaction_type) = 'PAYMENT'
     16  ;

    CUSTOMER_ID TRANSACTION_TYPE              TRANSACTION_AMOUNT
    ----------- ----------------------------- ------------------
              1 Payment,ReversePayment                         0
              1 payment,ReversePayment                         0
              1 Payment                                      400
              1 Payment                                      500


问:
Pandas filter where current row string contains string from previous row in different column
I have the following pandas DataFrame:

```<code>df = pd.DataFrame({'col1':['1', np.nan, '2', np.nan, np.nan, '3', '4', '7', np.nan], 'col2':[np.nan, '1,2', np.nan, '0,3', '0,3', np.nan, np.nan, np.nan, '7,8']})
</code>```

which looks like this:

```<code>  col1 col2
0    1  NaN
1  NaN  1,2
2    2  NaN
3  NaN  0,3
4  NaN  0,3
5    3  NaN
6    4  NaN
7    7  NaN
8  NaN  7,8
</code>```

I'm trying to figure out how to create a single vectorized filter that will return rows whose col2 value contain the col1 value from the previous row. If either col1 or col2 is NaN, the row should not be considered. Thus, on this df, the result should be:

```<code>1  NaN  1,2
8  NaN  7,8
</code>```

At first I considered shifting col1 down by one and using something like isin:

```<code> df[(df['col1'].shift(1).fillna('').isin(something in here)]
</code>```

But then i realized that isin doesn't handle each row separately, i.e it checks if each row is in the same list. So now i'm convinced i should be using something along the lines of df['col2'].str.contains(df['col2']) but i'm not quite sure how to handle the shifting and what not.

Again the goal is to have a vectorized filter such that i can do this:

```<code>filtered_rows = df[(filter_here)]
</code>```

I'd appreciate any help!

答:
```<code>df = pd.DataFrame({'col1':['1', np.nan, '2', np.nan, np.nan, '3', '4', '7', np.nan], 'col2':[np.nan, '1,2', np.nan, '0,3', '0,3', np.nan, np.nan, np.nan, '7,8']})
df['col1_shifted'] = df['col1'].shift(1)
mask = df.apply(
    lambda x: x.col1_shifted in str(x.col2).split(',')
    if x.col1_shifted
    else False, axis=1
)
filtered_rows = df[mask][['col1', 'col2']]

filtered_rows

  col1 col2
1  NaN  1,2
8  NaN  7,8
</code>```

Body:
I have the following pandas DataFrame:

df = pd.DataFrame({'col1':['1', np.nan, '2', np.nan, np.nan, '3', '4', '7', np.nan], 'col2':[np.nan, '1,2', np.nan, '0,3', '0,3', np.nan, np.nan, np.nan, '7,8']})

which looks like this:

  col1 col2
0    1  NaN
1  NaN  1,2
2    2  NaN
3  NaN  0,3
4  NaN  0,3
5    3  NaN
6    4  NaN
7    7  NaN
8  NaN  7,8

I'm trying to figure out how to create a single vectorized filter that will return rows whose col2 value contain the col1 value from the previous row. If either col1 or col2 is NaN, the row should not be considered. Thus, on this df, the result should be:

1  NaN  1,2
8  NaN  7,8

At first I considered shifting col1 down by one and using something like isin:

 df[(df['col1'].shift(1).fillna('').isin(something in here)]

But then i realized that isin doesn't handle each row separately, i.e it checks if each row is in the same list. So now i'm convinced i should be using something along the lines of df['col2'].str.contains(df['col2']) but i'm not quite sure how to handle the shifting and what not.

Again the goal is to have a vectorized filter such that i can do this:

filtered_rows = df[(filter_here)]

I'd appreciate any help!


问:
finding div height problem and changing margins commensurately
The various content DIVs show up in a slideshow style (I'm using Malsup's Cycle plugin) a single one at a time, but have differing heights (individually, and at different times the largest height may be different). The news div has the height of the highest content DIV. I would like to center the content DIVs vertically within the news DIV. Is there a simple way to do this with CSS? Or should I use jquery to calculate the height of newsWrapper, subtract the newsNav heights, and news from it, halve that and then add it as margin-top for each of the content DIVs?

```<code><div id="newsWrapper">
  <div id="newsNavTop">
  </div>
  <div id="news">
    <div>Content1</div>
    <div>Content2</div>
    <div>Content etc...</div>
  </div>
  <div id="newsNavBottom">
  </div>
</div>
</code>```

答:
you can try displaying this as table.

```<code>#news {
    display: table-cell;
    vertical-align: middle;
}

#news > div {
    display: block;
}
</code>```

http://jsfiddle.net/seler/P23DJ/

it wont work in ie lte 7

Body:
The various content DIVs show up in a slideshow style (I'm using Malsup's Cycle plugin) a single one at a time, but have differing heights (individually, and at different times the largest height may be different). The news div has the height of the highest content DIV. I would like to center the content DIVs vertically within the news DIV. Is there a simple way to do this with CSS? Or should I use jquery to calculate the height of newsWrapper, subtract the newsNav heights, and news from it, halve that and then add it as margin-top for each of the content DIVs?

Content1

Content2

Content etc...

Body:
you can try displaying this as table.

#news {
    display: table-cell;
    vertical-align: middle;
}

#news > div {
    display: block;
}

http://jsfiddle.net/seler/P23DJ/

it wont work in ie lte 7


问:
ServiceWorkerRegistration#installing values on repeat visit?
```<code>navigator.serviceWorker.register('/sw.js').then((reg)=>{
            console.log(reg.installing, " installing");
            console.log(reg.waiting, " waiting");
            console.log(reg.active, " active")
            reg.addEventListener('updatefound', function(){
                console.log("update found", reg.installing);
            })
})
</code>```

Case A) let's say user goes to the first time ever to my website. reg.installing prints worker object. reg.waiting and reg.active undefined which is understandable. updatefound runs immediatelly and reg.installing is the same worker as the above . All is good.

Case B) I updated SW code and deployed it. when refreshing the page, reg.installing prints undefined. Question 1) Why undefined? when refreshed, new service worker appears, but reg.installing is undefined.  in case A, when browser went to the website, a new service worker had to be installed, so reg.installing wasn't undefined.

My assumption: in my opinion, in Case B) then promise block happened faster than the browser actually compared old one with a new one, so when that happened, browser didn't have reg.installing at all.  and in Case A, because it was first time, browser didn't have to compare anything and it was faster enough to put worker in reg.installing.

Question 2) does my assumption make sense?

答:
I'd strongly recommend reading "The Service Worker Lifecycle" for an in-depth background.

The service worker lifecycle happens independently from any activities on client pages, and by the time your code executes, yes, it's entirely possible that the updated service worker has moved from the installing state to the waiting state (or active, if you've called skipWaiting()).

So yes, your assumption sounds like it would basically be correct.

Body:
navigator.serviceWorker.register('/sw.js').then((reg)=>{
            console.log(reg.installing, " installing");
            console.log(reg.waiting, " waiting");
            console.log(reg.active, " active")
            reg.addEventListener('updatefound', function(){
                console.log("update found", reg.installing);
            })
})

Case A) let's say user goes to the first time ever to my website. reg.installing prints worker object. reg.waiting and reg.active undefined which is understandable. updatefound runs immediatelly and reg.installing is the same worker as the above . All is good.

Case B) I updated SW code and deployed it. when refreshing the page, reg.installing prints undefined. Question 1) Why undefined? when refreshed, new service worker appears, but reg.installing is undefined.  in case A, when browser went to the website, a new service worker had to be installed, so reg.installing wasn't undefined.

My assumption: in my opinion, in Case B) then promise block happened faster than the browser actually compared old one with a new one, so when that happened, browser didn't have reg.installing at all.  and in Case A, because it was first time, browser didn't have to compare anything and it was faster enough to put worker in reg.installing.

Question 2) does my assumption make sense?


问:
SQL: Query the same column 3 times with 3 different where clauses
Trying to show a table with 3 columns that are prices that need to be displayed. the columns are differentiated by 'price_type' and there are 3 different price types.

Its probably something obvious im missing but something like:

```<code>Select price as 'current', price as '10min', price as '30min'
from table
where Price_Type(current) = 'current' AND Price_Type(10min) = '10min' AND
Price_Type(30min) = '30min'
Order by date desc
</code>```

I'm not sure what the actual syntax would be, but any help is appreciated.

答:
With conditional aggregation:</p>

```<code>select date,
  max(case when Price_Type = 'current' then price end) as [current],
  max(case when Price_Type = '10min' then price end) as [10min],
  max(case when Price_Type = '30min' then price end) as [30min]
from table
group by date
order by date desc
</code>```

Body:
Trying to show a table with 3 columns that are prices that need to be displayed. the columns are differentiated by 'price_type' and there are 3 different price types.

Its probably something obvious im missing but something like:

Select price as 'current', price as '10min', price as '30min'
from table
where Price_Type(current) = 'current' AND Price_Type(10min) = '10min' AND
Price_Type(30min) = '30min'
Order by date desc

I'm not sure what the actual syntax would be, but any help is appreciated.

Body:
With conditional aggregation:

select date,
  max(case when Price_Type = 'current' then price end) as [current],
  max(case when Price_Type = '10min' then price end) as [10min],
  max(case when Price_Type = '30min' then price end) as [30min]
from table
group by date
order by date desc


问:
Problems with JDBC URL in tomcat 9 context.xml for treeAnno
I have a fresh tomcat 9 installation on a server (Ubuntu 18.04). I am trying to set up treeanno (https://github.com/nilsreiter/treeanno/releases) and deploy the web application archive (war) which is given in the github repos.
I used the tomcat manager app in order to deploy the war-file, and followed this description to configure tomcat to use the respective database resource: https://github.com/nilsreiter/treeanno/blob/master/INSTALL.md.
According to the meagre description, this shall be added in the context.xml of the tomcat installation:

```<code><Resource name="treeanno/jdbc" auth="Container" type="javax.sql.DataSource"
           maxActive="100" maxIdle="30" maxWait="10000"
           username="USERNAME" password="PASSWORD" driverClassName="com.mysql.jdbc.Driver"
           url="DATABASE URL"/>
</code>```

As I am new to tomcat, it is unclear to me what properties I need to set, especially the "url".
If I try to access the app, I get the following error, pointing at that no data base connection can be build since the url is not adequate:

```<code>    Type Exception Report

    Message An exception occurred processing [/index.jsp] at line [12]

    Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

org.apache.jasper.JasperException: An exception occurred processing [/index.jsp] at line [12]

9:      doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN"
10:         doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
11:         omit-xml-declaration="false" />
12: <sql:query var="rs" dataSource="treeanno/jdbc" sql="select id, username from treeanno_users">
13: </sql:query>
14: <html xmlns="http://www.w3.org/1999/xhtml">
15: <head>

Stacktrace:
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:626)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:500)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

Root Cause

javax.servlet.ServletException: javax.servlet.jsp.JspException: Unable to get connection, DataSource invalid: "java.sql.SQLException: Cannot create JDBC driver of class 'com.mysql.jdbc.Driver' for connect URL 'jdbc:mysql:3306'"
    org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:666)
    org.apache.jsp.index_jsp._jspService(index_jsp.java:270)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:477)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

Root Cause

javax.servlet.jsp.JspException: Unable to get connection, DataSource invalid: "java.sql.SQLException: Cannot create JDBC driver of class 'com.mysql.jdbc.Driver' for connect URL 'jdbc:mysql:3306'"
    org.apache.taglibs.standard.tag.common.sql.QueryTagSupport.getConnection(QueryTagSupport.java:285)
    org.apache.taglibs.standard.tag.common.sql.QueryTagSupport.doStartTag(QueryTagSupport.java:168)
    org.apache.jsp.index_jsp._jspx_meth_sql_005fquery_005f0(index_jsp.java:296)
    org.apache.jsp.index_jsp._jspService(index_jsp.java:134)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:477)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
</code>```

I already figured out that the url is supposed to link to a database server including password and user, but this does not seem to be appropriate for this config file.

The following I found here (https://ci.apache.org/projects/tomcat/tomcat9/docs/jndi-datasource-examples-howto.html):

```<code>url=jdbc:mysql://localhost:3306/javatest"/
</code>```

but adjusting the port etc. does not work:
    url=jdbc:mysql://localhost:8080/TreeAnno-1.0.2"/

Now, how do I need to formulate the url to allow the app to connect to / initiate a MySQL database?

答:
There are various ways to configure a JDBC data connection for a Tomcat-hosted web application.

JNDI Connection in Tomcat

In your notes you describe how you are using a Tomcat Resource entry, added to the Tomcat context.xml file. When I use this approach, I also add an entry to my web application's web.xml file, which refers to the Resource entry.  For example:

```<code><resource-ref>
    <res-ref-name>treeanno/jdbc</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
</resource-ref>
</code>```

Note how the resource reference name in my web.xml file matches the Resource name.

Having done that, I can now refer to that data source in my application's Java code as follows:

```<code>// ABSOLUTELY NOT PRODUCTION-READY CODE! JUST FOR TESTING!

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

...

Context initialContext = new InitialContext();
Context context = (Context) initialContext.lookup("java:comp/env");
DataSource ds = (DataSource) context.lookup("treeanno/jdbc");
</code>```

What does that java:comp/env do?  See here.

But First Test Your URL

You may want to independently ensure that you have the correct JDBC connection URL (and user and pass), before you get into the above configuration.

No amount of tinkering will help if you have the wrong URL, or the data source is not available, etc.

How to test? Various ways - for example:

Use a tool such as DBeaver. This will ask for a URL, user, and password to connect to MySQL.

Or write a separate stand-alone Java app (with a main method) and a basic JDBC connection.

Or any other way that focuses only on the MySQL connection details, outside of the Tomcat configuration complications.

And as @CHN pointed out: this is all moot if you don't have the mysql JDBC jar file.

Like I say, this is only one way to get the job done - but it has worked for me.

Body:
I have a fresh tomcat 9 installation on a server (Ubuntu 18.04). I am trying to set up treeanno (https://github.com/nilsreiter/treeanno/releases) and deploy the web application archive (war) which is given in the github repos.
I used the tomcat manager app in order to deploy the war-file, and followed this description to configure tomcat to use the respective database resource: https://github.com/nilsreiter/treeanno/blob/master/INSTALL.md.
According to the meagre description, this shall be added in the context.xml of the tomcat installation:

<Resource name="treeanno/jdbc" auth="Container" type="javax.sql.DataSource"
           maxActive="100" maxIdle="30" maxWait="10000"
           username="USERNAME" password="PASSWORD" driverClassName="com.mysql.jdbc.Driver"
           url="DATABASE URL"/>

As I am new to tomcat, it is unclear to me what properties I need to set, especially the "url".
If I try to access the app, I get the following error, pointing at that no data base connection can be build since the url is not adequate:

    Type Exception Report

    Message An exception occurred processing [/index.jsp] at line [12]

    Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

org.apache.jasper.JasperException: An exception occurred processing [/index.jsp] at line [12]

9:      doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN"
10:         doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
11:         omit-xml-declaration="false" />
12: <sql:query var="rs" dataSource="treeanno/jdbc" sql="select id, username from treeanno_users">
13: </sql:query>
14:
15:

Stacktrace:
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:626)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:500)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

Root Cause

javax.servlet.ServletException: javax.servlet.jsp.JspException: Unable to get connection, DataSource invalid: "java.sql.SQLException: Cannot create JDBC driver of class 'com.mysql.jdbc.Driver' for connect URL 'jdbc:mysql:3306'"
    org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:666)
    org.apache.jsp.index_jsp._jspService(index_jsp.java:270)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:477)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

Root Cause

javax.servlet.jsp.JspException: Unable to get connection, DataSource invalid: "java.sql.SQLException: Cannot create JDBC driver of class 'com.mysql.jdbc.Driver' for connect URL 'jdbc:mysql:3306'"
    org.apache.taglibs.standard.tag.common.sql.QueryTagSupport.getConnection(QueryTagSupport.java:285)
    org.apache.taglibs.standard.tag.common.sql.QueryTagSupport.doStartTag(QueryTagSupport.java:168)
    org.apache.jsp.index_jsp._jspx_meth_sql_005fquery_005f0(index_jsp.java:296)
    org.apache.jsp.index_jsp._jspService(index_jsp.java:134)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:477)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

I already figured out that the url is supposed to link to a database server including password and user, but this does not seem to be appropriate for this config file.

The following I found here (https://ci.apache.org/projects/tomcat/tomcat9/docs/jndi-datasource-examples-howto.html):

url=jdbc:mysql://localhost:3306/javatest"/

but adjusting the port etc. does not work:
    url=jdbc:mysql://localhost:8080/TreeAnno-1.0.2"/

Now, how do I need to formulate the url to allow the app to connect to / initiate a MySQL database?

Body:
There are various ways to configure a JDBC data connection for a Tomcat-hosted web application.

JNDI Connection in Tomcat

In your notes you describe how you are using a Tomcat Resource entry, added to the Tomcat context.xml file. When I use this approach, I also add an entry to my web application's web.xml file, which refers to the Resource entry.  For example:

<resource-ref>
    <res-ref-name>treeanno/jdbc</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
</resource-ref>

Note how the resource reference name in my web.xml file matches the Resource name.

Having done that, I can now refer to that data source in my application's Java code as follows:

// ABSOLUTELY NOT PRODUCTION-READY CODE! JUST FOR TESTING!

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

...

Context initialContext = new InitialContext();
Context context = (Context) initialContext.lookup("java:comp/env");
DataSource ds = (DataSource) context.lookup("treeanno/jdbc");

What does that java:comp/env do?  See here.

But First Test Your URL

You may want to independently ensure that you have the correct JDBC connection URL (and user and pass), before you get into the above configuration.

No amount of tinkering will help if you have the wrong URL, or the data source is not available, etc.

How to test? Various ways - for example:

Use a tool such as DBeaver. This will ask for a URL, user, and password to connect to MySQL.

Or write a separate stand-alone Java app (with a main method) and a basic JDBC connection.

Or any other way that focuses only on the MySQL connection details, outside of the Tomcat configuration complications.

And as @CHN pointed out: this is all moot if you don't have the mysql JDBC jar file.

Like I say, this is only one way to get the job done - but it has worked for me.


问:
Jedis does not delete keys
I have just installed redis' last version on Ubuntu 18.04.3. I have tried out writing values directly with redis-cli.

```<code>127.0.0.1:6379> set myket somevalue
</code>```

I am now trying to delete all values from Jedis:

```<code>    Jedis jedis = new Jedis("localhost", 6379);
    Set<String> names=jedis.keys("NAME:*");
    System.out.println("There are " + names.size() +  " keys to delete");
    Iterator<String> it = names.iterator();
    while (it.hasNext()) {
        String s = it.next();
        jedis.del(s);
        System.out.println(s + " has been deleted");
    }
</code>```

However, it always says that there are 0 keys right now. When I query it from redis-clidirectly, it is still there. How can I delete the keys from Jedis?

答: Your key name is myket and your pattern is NAME:*. The pattern NAME:* doesn't match myket. That's why you're finding 0 matching keys.

Title: Jedis does not delete keys

Body:
I have just installed redis' last version on Ubuntu 18.04.3. I have tried out writing values directly with redis-cli.

127.0.0.1:6379> set myket somevalue

I am now trying to delete all values from Jedis:

    Jedis jedis = new Jedis("localhost", 6379);
    Set<String> names=jedis.keys("NAME:*");
    System.out.println("There are " + names.size() +  " keys to delete");
    Iterator<String> it = names.iterator();
    while (it.hasNext()) {
        String s = it.next();
        jedis.del(s);
        System.out.println(s + " has been deleted");
    }

However, it always says that there are 0 keys right now. When I query it from redis-clidirectly, it is still there. How can I delete the keys from Jedis?


问:
How can I avoid duplicated functions using MVC?
I'm building an application using ASP.NET Core, and I would like to avoid duplicated code, in the following situation. I'm using usermanager to get all users with a specific role, but I'm using the exact same function for three diferent controllers because I don't know how to reuse the function.

I've read about action filters, but I don't know how to adapt my code in this situation.

Example first controller:

```<code>public class FirstController : Controller
{
    private readonly UserManager<ApplicationUser> _userManager;

    public async Task<IActionResult> Index()
    {
        Dictionary<string, string> emails = await GetAdminEmails();
        ViewBag.Emails = emails;
    }

    private async Task<Dictionary<string, string>> GetAdminEmails()
    {
        Dictionary<string, string> emails = new Dictionary<string, string>();

        foreach (var email in _userManager.Users.ToList())
        {
            var user = await _userManager.FindByEmailAsync(email.Email);
            var roles = await _userManager.GetRolesAsync(user);

            foreach (var role in roles)
            {
                if (role == "Admin")
                {
                    emails.Add(email.Email, email.Id);
                }
            }
        }

        return emails;
    }
}
</code>```

Second controller

```<code>public class SecondController : Controller
{
    private readonly UserManager<ApplicationUser> _userManager;

    public async Task<IActionResult> Index()
    {
        Dictionary<string, string> emails = await GetAdminEmails();
        ViewBag.Emails = emails;
    }

    private async Task<Dictionary<string, string>> GetAdminEmails()
    {
        Dictionary<string, string> emails = new Dictionary<string, string>();

        foreach (var email in _userManager.Users.ToList())
        {
            var user = await _userManager.FindByEmailAsync(email.Email);
            var roles = await _userManager.GetRolesAsync(user);

            foreach (var role in roles)
            {
                if (role == "Admin")
                {
                    emails.Add(email.Email, email.Id);
                }
            }
        }

        return emails;
    }
}
</code>```

Third controller

```<code>public class ThirdController : Controller
{
    private readonly UserManager<ApplicationUser> _userManager;

    public async Task<IActionResult> Index()
    {
        Dictionary<string, string> emails = await GetAdminEmails();
        ViewBag.Emails = emails;
    }

    private async Task<Dictionary<string, string>> GetAdminEmails()
    {
        Dictionary<string, string> emails = new Dictionary<string, string>();

        foreach (var email in _userManager.Users.ToList())
        {
            var user = await _userManager.FindByEmailAsync(email.Email);
            var roles = await _userManager.GetRolesAsync(user);

            foreach (var role in roles)
            {
                if (role == "Admin")
                {
                    emails.Add(email.Email, email.Id);
                }
            }
        }

        return emails;
    }
}
</code>```

答:
You can put GetAdminEmails in a separate class like this:

```<code>public interface IEmailManager
{
    public Task<Dictionary<string, string>> GetAdminEmails(UserManager<ApplicationUser> userManager);
}
</code>```

Implement the interface

```<code>public class EmailManager : IEmailManager
{
    public async Task<Dictionary<string, string>> GetAdminEmails(UserManager<ApplicationUser> userManager)
    {
        Dictionary<string, string> emails = new Dictionary<string, string>();

        foreach (var email in userManager.Users.ToList())
        {
            var user = await userManager.FindByEmailAsync(email.Email);
            var roles = await userManager.GetRolesAsync(user);

            foreach (var role in roles)
            {
                if (role == "Admin")
                {
                    emails.Add(email.Email, email.Id);
                }
            }
        }

        return emails;
    }
}
</code>```

First Controller

```<code>public class FirstController : Controller
{
    private readonly UserManager<ApplicationUser> userManager;
    private readonly IEmailManager emailManager;

    public FirstController(UserManager<ApplicationUser> userManager, IEmailManager emailManager)
    {
        this.userManager = userManager;
        this.emailManager = emailManager;
    }

    public async Task<IActionResult> Index() =>
        ViewBag.Emails = await this.emailManager.GetAdminEmails(userManager);
}
</code>```

Second Controller

```<code>public class SecondController : Controller
{
    private readonly UserManager<ApplicationUser> userManager;
    private readonly IEmailManager emailManager;

    public SecondController(UserManager<ApplicationUser> userManager, IEmailManager emailManager)
    {
        this.userManager = userManager;
        this.emailManager = emailManager;
    }

    public async Task<IActionResult> Index() =>
        ViewBag.Emails = await this.emailManager.GetAdminEmails(userManager);
}
</code>```

Body:
I'm building an application using ASP.NET Core, and I would like to avoid duplicated code, in the following situation. I'm using usermanager to get all users with a specific role, but I'm using the exact same function for three diferent controllers because I don't know how to reuse the function.

I've read about action filters, but I don't know how to adapt my code in this situation.

Example first controller:

public class FirstController : Controller
{
    private readonly UserManager<ApplicationUser> _userManager;

    public async Task<IActionResult> Index()
    {
        Dictionary<string, string> emails = await GetAdminEmails();
        ViewBag.Emails = emails;
    }

    private async Task<Dictionary<string, string>> GetAdminEmails()
    {
        Dictionary<string, string> emails = new Dictionary<string, string>();

        foreach (var email in _userManager.Users.ToList())
        {
            var user = await _userManager.FindByEmailAsync(email.Email);
            var roles = await _userManager.GetRolesAsync(user);

            foreach (var role in roles)
            {
                if (role == "Admin")
                {
                    emails.Add(email.Email, email.Id);
                }
            }
        }

        return emails;
    }
}

Second controller

public class SecondController : Controller
{
    private readonly UserManager<ApplicationUser> _userManager;

    public async Task<IActionResult> Index()
    {
        Dictionary<string, string> emails = await GetAdminEmails();
        ViewBag.Emails = emails;
    }

    private async Task<Dictionary<string, string>> GetAdminEmails()
    {
        Dictionary<string, string> emails = new Dictionary<string, string>();

        foreach (var email in _userManager.Users.ToList())
        {
            var user = await _userManager.FindByEmailAsync(email.Email);
            var roles = await _userManager.GetRolesAsync(user);

            foreach (var role in roles)
            {
                if (role == "Admin")
                {
                    emails.Add(email.Email, email.Id);
                }
            }
        }

        return emails;
    }
}

Third controller

public class ThirdController : Controller
{
    private readonly UserManager<ApplicationUser> _userManager;

    public async Task<IActionResult> Index()
    {
        Dictionary<string, string> emails = await GetAdminEmails();
        ViewBag.Emails = emails;
    }

    private async Task<Dictionary<string, string>> GetAdminEmails()
    {
        Dictionary<string, string> emails = new Dictionary<string, string>();

        foreach (var email in _userManager.Users.ToList())
        {
            var user = await _userManager.FindByEmailAsync(email.Email);
            var roles = await _userManager.GetRolesAsync(user);

            foreach (var role in roles)
            {
                if (role == "Admin")
                {
                    emails.Add(email.Email, email.Id);
                }
            }
        }

        return emails;
    }
}

Body:
You can put GetAdminEmails in a separate class like this:

public interface IEmailManager
{
    public Task<Dictionary<string, string>> GetAdminEmails(UserManager<ApplicationUser> userManager);
}

Implement the interface

public class EmailManager : IEmailManager
{
    public async Task<Dictionary<string, string>> GetAdminEmails(UserManager<ApplicationUser> userManager)
    {
        Dictionary<string, string> emails = new Dictionary<string, string>();

        foreach (var email in userManager.Users.ToList())
        {
            var user = await userManager.FindByEmailAsync(email.Email);
            var roles = await userManager.GetRolesAsync(user);

            foreach (var role in roles)
            {
                if (role == "Admin")
                {
                    emails.Add(email.Email, email.Id);
                }
            }
        }

        return emails;
    }
}

First Controller

public class FirstController : Controller
{
    private readonly UserManager<ApplicationUser> userManager;
    private readonly IEmailManager emailManager;

    public FirstController(UserManager<ApplicationUser> userManager, IEmailManager emailManager)
    {
        this.userManager = userManager;
        this.emailManager = emailManager;
    }

    public async Task<IActionResult> Index() =>
        ViewBag.Emails = await this.emailManager.GetAdminEmails(userManager);
}

Second Controller

public class SecondController : Controller
{
    private readonly UserManager<ApplicationUser> userManager;
    private readonly IEmailManager emailManager;

    public SecondController(UserManager<ApplicationUser> userManager, IEmailManager emailManager)
    {
        this.userManager = userManager;
        this.emailManager = emailManager;
    }

    public async Task<IActionResult> Index() =>
        ViewBag.Emails = await this.emailManager.GetAdminEmails(userManager);
}


问:
uwp UniformGrid has unwanted vertical spacing between rows
I have multiple textboxes which I want fill in a proper flow from left to right in fixed 2 columns, because there is runtime logic in code behind where any of the textboxes visibility can be changed so I want all visible boxes at any given time to be aligned properly so that is why I am using UniformGrid from community toolkit, but there is some Unwanted vertical spacing between all the rows.

sample project to reproduce the issue : https://github.com/touseefbsb/UniformGridIssue

sample code

```<code><Grid>
    <controls:UniformGrid
        x:Name="CommonPanel"
        Background="Brown"
        Columns="2"
        Orientation="Horizontal">
        <TextBox Height="112" HorizontalAlignment="Stretch" />
        <TextBox Height="112" HorizontalAlignment="Stretch" />
        <TextBox Height="112" HorizontalAlignment="Stretch" />
        <TextBox Height="112" HorizontalAlignment="Stretch" />
        <TextBox Height="112" HorizontalAlignment="Stretch" />
        <TextBox Height="112" HorizontalAlignment="Stretch" />
        <TextBox Height="112" HorizontalAlignment="Stretch" />
        <TextBox Height="112" HorizontalAlignment="Stretch" />
        <TextBox Height="112" HorizontalAlignment="Stretch" />
        <TextBox Height="112" HorizontalAlignment="Stretch" />
        <TextBox Height="112" HorizontalAlignment="Stretch" />
    </controls:UniformGrid>
</Grid>
</code>```

There seems to be some sort of margin about 27 both up and down of each item, I am not sure where it is coming from though.

Update 1

this was a sample project,my original project has each textbox with 112 height and some have double that and we also might generate some of them dynamically so I guess I might need to separate the big height textboxes but is there a way I can set same height for all rows? Considering I won't know exact number of rows?

I tried following but it gave me 112 height just for 1st row.

答:
There are two components at play, the space between the TextBoxes (the 27px) and the border.

If you select in any of those TextBoxes, you'll see the border color changes to Blue. If you hover over them, you'll see the visual state of those same borders change.

To remove it, set BorderThickness to 0:

<TextBox Height="112"
         HorizontalAlignment="Stretch"
         BorderThickness="0"/>
```

<p>Or make this easier for yourself and create an Implicit TextBox Style:</p>

<pre class="lang-xml prettyprint-override"><code><controls:UniformGrid x:Name="CommonPanel"
                      Background="Brown"
                      Columns="2"
                      Orientation="Horizontal">
    <controls:UniformGrid.Resources>
        <Style TargetType="TextBox">
            <Setter Property="Height"
                    Value="112" />
            <Setter Property="HorizontalAlignment"
                    Value="Stretch" />
            <Setter Property="BorderThickness"
                    Value="0" />
        </Style>
    </controls:UniformGrid.Resources>
    <TextBox />
    <TextBox />
    <TextBox />
    <TextBox />
    <TextBox />
    <TextBox />
    <TextBox />
    <TextBox />
    <TextBox />
    <TextBox />
    <TextBox />
</controls:UniformGrid>
</code>```

Now, let's discuss the remaining pixel padding. You've hard coded the Height of the TextBox, this restricts how much it can fill the space. To remove that padding, take it out of the style:

```

<h2>Understanding Layout</h2>

<p>I wanted to add some addition information in case you're trying to force the rows to fit into 112 pixels.</p>

<p>You can think of the UniformGrid as manually adding RowDefinition and ColumnDefinition yourself.</p>

<pre class="lang-xml prettyprint-override"><code><Grid>
    <Grid.RowDefinitions>
        <!-- One of these is created for every row needed  -->
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <!-- One of these is created for every column needed  -->
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
</Grid>

</code>```

Since you have 11 children in the UniformGrid and set the columns 2, it is virtually identical to this:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="*" />
        <RowDefinition Height="*" />
        <RowDefinition Height="*" />
        <RowDefinition Height="*" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>

    <TextBox Grid.Row="0"
             Grid.Column="0"/>
    <TextBox Grid.Row="0"
             Grid.Column="1" />
    <TextBox Grid.Row="1"
             Grid.Column="0" />
    <TextBox Grid.Row="1"
             Grid.Column="1" />
    <TextBox Grid.Row="2"
             Grid.Column="0" />
    <TextBox Grid.Row="2"
             Grid.Column="1" />
    <TextBox Grid.Row="3"
             Grid.Column="0" />
    <TextBox Grid.Row="3"
             Grid.Column="1" />
    <TextBox Grid.Row="4"
             Grid.Column="1" />
    <TextBox Grid.Row="5"
             Grid.Column="0" />
    <TextBox Grid.Row="5"
             Grid.Column="1" />
</Grid>
```

<h3>UPDATE</h3>

<p>You can override the sizing of the <code>UniformGrid</code> RowDefinitions dynamically after it has loaded. This will let the row height shrink to the 112 pixels that the TextBoxes are using.</p>

<p>XAML - Subscribe to the Loaded event</p>

<pre class="lang-ml prettyprint-override"><code><controls:UniformGrid x:Name="CommonPanel" Loaded="CommonPanel_Loaded" .../>
``

```csharp
// Will fire when the UniformGrid is loaded
private void CommonPanel_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
    // Iterate over all the RowDefinitions
    for (int i = 0; i < CommonPanel.RowDefinitions.Count - 1; i++)
    {
        // FEATURE - Here you override the Star-Height with Auto height
        CommonPanel.RowDefinitions[i].Height = GridLength.Auto;
    }
}
```

<p>Finally, there is one last step to make sure the last row's TextBoxes are aligned correctly. Set the style's VerticalAlignment to Top:</p>

<pre class="lang-xml prettyprint-override"><code><Style TargetType="TextBox">
    <Setter Property="Height"
            Value="112" />
    <Setter Property="HorizontalAlignment"
            Value="Stretch" />
    <Setter Property="VerticalAlignment"
            Value="Top" />
    <Setter Property="BorderThickness"
            Value="0" />
</Style>
</code>```

Important
If you are adding new items to the UniformGrid at runtime, you will need to re-run that logic again.

Body:
I have multiple textboxes which I want fill in a proper flow from left to right in fixed 2 columns, because there is runtime logic in code behind where any of the textboxes visibility can be changed so I want all visible boxes at any given time to be aligned properly so that is why I am using UniformGrid from community toolkit, but there is some Unwanted vertical spacing between all the rows.

sample project to reproduce the issue : https://github.com/touseefbsb/UniformGridIssue

sample code

<Grid>
    <controls:UniformGrid
        x:Name="CommonPanel"
        Background="Brown"
        Columns="2"
        Orientation="Horizontal">
        <TextBox Height="112" HorizontalAlignment="Stretch" />
        <TextBox Height="112" HorizontalAlignment="Stretch" />
        <TextBox Height="112" HorizontalAlignment="Stretch" />
        <TextBox Height="112" HorizontalAlignment="Stretch" />
        <TextBox Height="112" HorizontalAlignment="Stretch" />
        <TextBox Height="112" HorizontalAlignment="Stretch" />
        <TextBox Height="112" HorizontalAlignment="Stretch" />
        <TextBox Height="112" HorizontalAlignment="Stretch" />
        <TextBox Height="112" HorizontalAlignment="Stretch" />
        <TextBox Height="112" HorizontalAlignment="Stretch" />
        <TextBox Height="112" HorizontalAlignment="Stretch" />
    </controls:UniformGrid>
</Grid>

There seems to be some sort of margin about 27 both up and down of each item, I am not sure where it is coming from though.

Update 1

this was a sample project,my original project has each textbox with 112 height and some have double that and we also might generate some of them dynamically so I guess I might need to separate the big height textboxes but is there a way I can set same height for all rows? Considering I won't know exact number of rows?

I tried following but it gave me 112 height just for 1st row.

Body:
There are two components at play, the space between the TextBoxes (the 27px) and the border.

If you select in any of those TextBoxes, you'll see the border color changes to Blue. If you hover over them, you'll see the visual state of those same borders change.

To remove it, set BorderThickness to 0:

<TextBox Height="112"
         HorizontalAlignment="Stretch"
         BorderThickness="0"/>

Or make this easier for yourself and create an Implicit TextBox Style:

<controls:UniformGrid x:Name="CommonPanel"
                      Background="Brown"
                      Columns="2"
                      Orientation="Horizontal">
    <controls:UniformGrid.Resources>
        <Style TargetType="TextBox">
            <Setter Property="Height"
                    Value="112" />
            <Setter Property="HorizontalAlignment"
                    Value="Stretch" />
            <Setter Property="BorderThickness"
                    Value="0" />
        </Style>
    </controls:UniformGrid.Resources>
    <TextBox />
    <TextBox />
    <TextBox />
    <TextBox />
    <TextBox />
    <TextBox />
    <TextBox />
    <TextBox />
    <TextBox />
    <TextBox />
    <TextBox />
</controls:UniformGrid>

Now, let's discuss the remaining pixel padding. You've hard coded the Height of the TextBox, this restricts how much it can fill the space. To remove that padding, take it out of the style:

<Style TargetType="TextBox">
     <Setter Property="HorizontalAlignment" Value="Stretch" />
     <Setter Property="VerticalAlignment" Value="Stretch" />
     <Setter Property="BorderThickness" Value="0" />
</Style>

Understanding Layout

I wanted to add some addition information in case you're trying to force the rows to fit into 112 pixels.

You can think of the UniformGrid as manually adding RowDefinition and ColumnDefinition yourself.

<Grid>
    <Grid.RowDefinitions>
        <!-- One of these is created for every row needed  -->
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <!-- One of these is created for every column needed  -->
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
</Grid>

Since you have 11 children in the UniformGrid and set the columns 2, it is virtually identical to this:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="*" />
        <RowDefinition Height="*" />
        <RowDefinition Height="*" />
        <RowDefinition Height="*" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>

    <TextBox Grid.Row="0"
             Grid.Column="0"/>
    <TextBox Grid.Row="0"
             Grid.Column="1" />
    <TextBox Grid.Row="1"
             Grid.Column="0" />
    <TextBox Grid.Row="1"
             Grid.Column="1" />
    <TextBox Grid.Row="2"
             Grid.Column="0" />
    <TextBox Grid.Row="2"
             Grid.Column="1" />
    <TextBox Grid.Row="3"
             Grid.Column="0" />
    <TextBox Grid.Row="3"
             Grid.Column="1" />
    <TextBox Grid.Row="4"
             Grid.Column="1" />
    <TextBox Grid.Row="5"
             Grid.Column="0" />
    <TextBox Grid.Row="5"
             Grid.Column="1" />
</Grid>

UPDATE

You can override the sizing of the UniformGrid RowDefinitions dynamically after it has loaded. This will let the row height shrink to the 112 pixels that the TextBoxes are using.

XAML - Subscribe to the Loaded event

<controls:UniformGrid x:Name="CommonPanel" Loaded="CommonPanel_Loaded" .../>
``

```csharp
// Will fire when the UniformGrid is loaded
private void CommonPanel_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
    // Iterate over all the RowDefinitions
    for (int i = 0; i < CommonPanel.RowDefinitions.Count - 1; i++)
    {
        // FEATURE - Here you override the Star-Height with Auto height
        CommonPanel.RowDefinitions[i].Height = GridLength.Auto;
    }
}

Finally, there is one last step to make sure the last row's TextBoxes are aligned correctly. Set the style's VerticalAlignment to Top:

<Style TargetType="TextBox">
    <Setter Property="Height"
            Value="112" />
    <Setter Property="HorizontalAlignment"
            Value="Stretch" />
    <Setter Property="VerticalAlignment"
            Value="Top" />
    <Setter Property="BorderThickness"
            Value="0" />
</Style>

Important
If you are adding new items to the UniformGrid at runtime, you will need to re-run that logic again.


问:
"Could not run phased build action using Gradle distribution..." error in Flutter
I simply changed my package name in flutter by editing .xml and gradle file(s) and changing the folder names in src/main/kotlin/my/package/name. After that action there is "1" sign in front of Android folder, but  does not redirect me to any file that has error, I assume error is in the folder (structure) itself and maybe changing folder names in /kotlin/ folder caused it.

答: Uninstalling the "Java Dependency Viewer" extension in VSCode fixed it for me...might be worth a try. I'm only writing in Kotlin, so I didn't need it.</p>


问:
Set background in autocomplete view android
How i can set an image as background of my autocomlete list?

```<code>    <?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:textSize="16sp"
    android:textColor="#000">
</TextView>

AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete_friends);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, friendsListNameOrder);
    textView.setAdapter(adapter);
</code>```

Thank you

答:
in your xml put the background attribute for your TextView:</p>

```<code><TextView android:background="@drawable/your_img" ... other attributes />
</code>```

Body:
How i can set an image as background of my autocomlete list?

    <?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:textSize="16sp"
    android:textColor="#000">
</TextView>

AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete_friends);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, friendsListNameOrder);
    textView.setAdapter(adapter);

Thank you

Body:
in your xml put the background attribute for your TextView:

<TextView android:background="@drawable/your_img" ... other attributes />


问:
How to compute a value from two MySQL database columns for use in WHERE clause
I have a query that starts like...

```<code>SELECT session_id, time, quantity, teacher, sum(time+(quantity*60*60*60)) AS end FROM my_table WHERE end > 1582214400
</code>```

I am getting a PDO exception...

```<code>column not found: 1054 Unknown column 'end' in 'where clause'
</code>```

Why is PDO/MySQL giving me this error?  What is the correct syntax to compute end so I can use it in the WHERE clause?

答:
Jens is right on target that you can't use the alias end like the way you did. There are a couple other ways you can write the query also. Since that was too long for a comment, I added an answer.

Here's an alternate way of writing the query. Notice that I have explicitly used group by clause.

```<code>SELECT
  session_id,
  time,
  quantity,
  teacher,
  sum(time+(quantity*60*60*60)) AS end
FROM my_table
GROUP BY
  session_id,
  time,
  quantity,
  teacher
HAVING sum(time+(quantity*60*60*60)) > 1582214400
</code>```

or you could use a subquery, which could be inefficient.

```<code>SELECT * FROM (

  SELECT
    session_id,
    time,
    quantity,
    teacher,
    sum(time+(quantity*60*60*60)) AS end
  FROM my_table
  GROUP BY
    session_id,
    time,
    quantity,
    teacher

) main
WHERE end > 1582214400
</code>```

Body:
I have a query that starts like...

SELECT session_id, time, quantity, teacher, sum(time+(quantity*60*60*60)) AS end FROM my_table WHERE end > 1582214400

I am getting a PDO exception...

column not found: 1054 Unknown column 'end' in 'where clause'

Why is PDO/MySQL giving me this error?  What is the correct syntax to compute end so I can use it in the WHERE clause?

Body:
Jens is right on target that you can't use the alias end like the way you did. There are a couple other ways you can write the query also. Since that was too long for a comment, I added an answer.

Here's an alternate way of writing the query. Notice that I have explicitly used group by clause.

SELECT
  session_id,
  time,
  quantity,
  teacher,
  sum(time+(quantity*60*60*60)) AS end
FROM my_table
GROUP BY
  session_id,
  time,
  quantity,
  teacher
HAVING sum(time+(quantity*60*60*60)) > 1582214400

or you could use a subquery, which could be inefficient.

SELECT * FROM (

  SELECT
    session_id,
    time,
    quantity,
    teacher,
    sum(time+(quantity*60*60*60)) AS end
  FROM my_table
  GROUP BY
    session_id,
    time,
    quantity,
    teacher

) main
WHERE end > 1582214400


问:
Unable to select radio button in UI when groupValue supplied using futurebuilder
I am trying to use flutter to create a form with radio button and it is not working. I have shown a minimal code below.

When I supply groupValue using FutureBuilder, I am unable to select radio button other than default which is already selected. This is probably happening because setState is running FutureBuilder every time. Is there a way to get around this?

```<code>import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

const appName = 'Radio Example';

void main() => runApp(MaterialApp(
      title: appName,
      home: MyHomePage(),
    ));

class MyHomePage extends StatefulWidget {
  @override
  MyHomePageState createState() => MyHomePageState();
}

class MyHomePageState extends State<MyHomePage> {
  Future<int> getSelected() async {
    return 1;
  }

  int selectedRadio;

  setSelectedRadio(int val) {
    setState(() {
      selectedRadio = val;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text(appName)),
        body: Column(
          children: <Widget>[
            Expanded(
                child: FutureBuilder(
                    future: getSelected(),
                    builder: (context, snapshot) {
                      var newData = snapshot.data;
                      if (newData == null) {
                        return Container(
                          child: Center(
                            child: Text('Loading...'),
                          ),
                        );
                      } else {
                        selectedRadio = newData;
                        return ListView(
                          padding: EdgeInsets.all(24),
                          children: <Widget>[
                            Radio(
                              value: 0,
                              groupValue: selectedRadio,
                              onChanged: (val) {
                                //print("Radio activated");
                                setSelectedRadio(val);
                              },
                            ),
                            Radio(
                              value: 1,
                              groupValue: selectedRadio,
                              onChanged: (val) {
                                //print("Radio activated");
                                setSelectedRadio(val);
                              },
                            ),
                            RaisedButton(
                                child: Text("Save"),
                                onPressed: () {
                                  print("Selected Radio: $selectedRadio");
                                })
                          ],
                        );
                      }
                    })),
          ],
        ));
  }
}
</code>```

答:
I faced this problem before, although I wasn't using FutureBuilder but this problem occurred while I was trying to create RadioButtons dynamically. Finally I came up with these lines of code:

```<code>  List<Widget> createRows() {
   List<Widget> allRows = new List();
   for (int i = 0; i < rawQuestions.length; i++) {
     allRows.add(Directionality(
       textDirection: TextDirection.rtl,
       child: RadioListTile<String>(
         title: Text(
           rawQuestions[i].toString(),
         ),
         activeColor: Colors.teal,
         groupValue: _radioValue,
         value: rawQuestions[i].toString(),
         onChanged: (value) {
           this.setState(() {
             _radioValue = value;
           });
         },
       ),
     ));
   }
   return allRows;
}
</code>```

Body:
I am trying to use flutter to create a form with radio button and it is not working. I have shown a minimal code below.

When I supply groupValue using FutureBuilder, I am unable to select radio button other than default which is already selected. This is probably happening because setState is running FutureBuilder every time. Is there a way to get around this?

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

const appName = 'Radio Example';

void main() => runApp(MaterialApp(
      title: appName,
      home: MyHomePage(),
    ));

class MyHomePage extends StatefulWidget {
  @override
  MyHomePageState createState() => MyHomePageState();
}

class MyHomePageState extends State<MyHomePage> {
  Future<int> getSelected() async {
    return 1;
  }

  int selectedRadio;

  setSelectedRadio(int val) {
    setState(() {
      selectedRadio = val;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text(appName)),
        body: Column(
          children: <Widget>[
            Expanded(
                child: FutureBuilder(
                    future: getSelected(),
                    builder: (context, snapshot) {
                      var newData = snapshot.data;
                      if (newData == null) {
                        return Container(
                          child: Center(
                            child: Text('Loading...'),
                          ),
                        );
                      } else {
                        selectedRadio = newData;
                        return ListView(
                          padding: EdgeInsets.all(24),
                          children: <Widget>[
                            Radio(
                              value: 0,
                              groupValue: selectedRadio,
                              onChanged: (val) {
                                //print("Radio activated");
                                setSelectedRadio(val);
                              },
                            ),
                            Radio(
                              value: 1,
                              groupValue: selectedRadio,
                              onChanged: (val) {
                                //print("Radio activated");
                                setSelectedRadio(val);
                              },
                            ),
                            RaisedButton(
                                child: Text("Save"),
                                onPressed: () {
                                  print("Selected Radio: $selectedRadio");
                                })
                          ],
                        );
                      }
                    })),
          ],
        ));
  }
}

Body:
I faced this problem before, although I wasn't using FutureBuilder but this problem occurred while I was trying to create RadioButtons dynamically. Finally I came up with these lines of code:

  List<Widget> createRows() {
   List<Widget> allRows = new List();
   for (int i = 0; i < rawQuestions.length; i++) {
     allRows.add(Directionality(
       textDirection: TextDirection.rtl,
       child: RadioListTile<String>(
         title: Text(
           rawQuestions[i].toString(),
         ),
         activeColor: Colors.teal,
         groupValue: _radioValue,
         value: rawQuestions[i].toString(),
         onChanged: (value) {
           this.setState(() {
             _radioValue = value;
           });
         },
       ),
     ));
   }
   return allRows;
}


问:
Batch for loop to execute java - how to dereference variable as part of command
Given this file myfile.txt:

```<code>-Dvariable=a -Dvariable2=b -Dvariable3=c
-Dvariable=a -Dvariable2=b -Dvariable3=d
-Dvariable=a -Dvariable2=b -Dvariable3=e
</code>```

and batch.bat:

```<code>for /F "tokens=*" %%A in (myfile.txt) do (
    C:\javapath\java.exe %%A -XX:..... -classpath....... main.Main
)
</code>```

How can I make %%A dereference as program arguments?

With the above, the output is: (i.e. its just stopping after java.exe)

```<code>(C:\javapath\java.exe)
Usage: java [-options] class [args...] //etc....
</code>```

With doing set first, I simply get spaces:

```<code>batch.bat:
set x=%%A
C:\javapath\java.exe %x% -XX:..... -classpath....... main.Main

output:
set x=-Dvariable=a -Dvariable2=b -Dvariable3=c
C:\javapath\java.exe  -XX:..... -classpath....... main.Main
</code>```

答:
With thanks to @Mofi.</p>

```<code>for /F "usebackq delims=" %%I in (myfile.txt) do (
    C:\javapath\java.exe %%I -XX:..... -classpath....... main.Main
)
</code>```

Body:
Given this file myfile.txt:

-Dvariable=a -Dvariable2=b -Dvariable3=c
-Dvariable=a -Dvariable2=b -Dvariable3=d
-Dvariable=a -Dvariable2=b -Dvariable3=e

and batch.bat:

for /F "tokens=*" %%A in (myfile.txt) do (
    C:\javapath\java.exe %%A -XX:..... -classpath....... main.Main
)

How can I make %%A dereference as program arguments?

With the above, the output is: (i.e. its just stopping after java.exe)

(C:\javapath\java.exe)
Usage: java [-options] class [args...] //etc....

With doing set first, I simply get spaces:

batch.bat:
set x=%%A
C:\javapath\java.exe %x% -XX:..... -classpath....... main.Main

output:
set x=-Dvariable=a -Dvariable2=b -Dvariable3=c
C:\javapath\java.exe  -XX:..... -classpath....... main.Main

Body:
With thanks to @Mofi.

for /F "usebackq delims=" %%I in (myfile.txt) do (
    C:\javapath\java.exe %%I -XX:..... -classpath....... main.Main
)