问:
Display PyQt5 widget from background process
I want to write a python program run on background, and displaying PyQt5 GUI from background process on neccessary.

My solution is use RabbitMQ to do IPC work. program start with PyQt run on main thread, and start a thread listening RabbitMQ to show GUI on call.

Here is the code:

```<code>from PyQt5.QtWidgets import QApplication, QLabel
from PyQt5.QtCore import QThreadPool, QObject, QRunnable, pyqtSignal
import traceback
import pika
import sys

class RabbitMQSignals(QObject):
    target = pyqtSignal(int)

class MessageListener(QRunnable):

    def __init__(self):
        super(MessageListener, self).__init__()

        self.signals = RabbitMQSignals()

    def run(self):
        self.connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
        self.channel = self.connection.channel()
        self.channel.queue_declare(queue='ui')
        self.channel.basic_consume(queue='ui', on_message_callback=self.dispatch, auto_ack=True)
        print('Waiting for signals')
        self.channel.start_consuming()

    def dispatch(self, channel, method, properties, body):
        body = body.decode('utf-8')
        if body == 'quit':
            sys.exit(0)

        print('[x] Received %s' % body)
        self.signals.target.emit(0)

class MainWidget(QObject):

    def __init__(self):
        super(MainWidget, self).__init__()

    def show(self, action):
        try:
            print('[x] Dispatched :' + str(action))
            label = QLabel('Hello World')
            label.show()
        except:
            print(traceback.format_exc())

if __name__ == '__main__':
    app = QApplication([])

    widget = MainWidget()
    pool = QThreadPool()
    listener = MessageListener()
    listener.signals.target.connect(widget.show)
    pool.start(listener)

    app.exec_()
</code>```

Now, everything works fine except that the label.show line crashes the program, no widget displayed, no message printed.

The client part is listed below, sending quit to quit the server.

```<code>import pika

connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='ui')
channel.basic_publish(exchange='', routing_key='ui', body='show label')
connection.close()
</code>```

My question is, how and why the label.show() shutdown the program without any error? How can I improve the program?

Or is there alternative ways to do the job?

Any suggestions are welcome.

Thank you in advance.

答:
The problem is that QLabel is a local variable so it will be deleted a moment after the show method is executed. The above should not cause the application to terminate but by default QApplication will be closed if at any time after showing at least one window they all close, in your case QLabel is displayed for a moment and closes, which consequently implies that the application it closes.

So the solution is to make the label a member of the class so that it is not deleted:

# ...
class MainWidget(QObject):
    def __init__(self):
        super(MainWidget, self).__init__()
        self.label = QLabel("Hello World")

    def show(self, action):
        print('[x] Dispatched :' + str(action))
        self.label.show()
# ...
```

On the other hand, Qt does not return exceptions when some function/method fails in its task, instead it informs us of the success of the execution through a variable, this does it for reasons of efficiency. And that same PyQt inherits so in 99.99% of the python code is not necessary to use try-except.

Body:
I want to write a python program run on background, and displaying PyQt5 GUI from background process on neccessary.

My solution is use RabbitMQ to do IPC work. program start with PyQt run on main thread, and start a thread listening RabbitMQ to show GUI on call.

Here is the code:

from PyQt5.QtWidgets import QApplication, QLabel
from PyQt5.QtCore import QThreadPool, QObject, QRunnable, pyqtSignal
import traceback
import pika
import sys

class RabbitMQSignals(QObject):
    target = pyqtSignal(int)

class MessageListener(QRunnable):

    def __init__(self):
        super(MessageListener, self).__init__()

        self.signals = RabbitMQSignals()

    def run(self):
        self.connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
        self.channel = self.connection.channel()
        self.channel.queue_declare(queue='ui')
        self.channel.basic_consume(queue='ui', on_message_callback=self.dispatch, auto_ack=True)
        print('Waiting for signals')
        self.channel.start_consuming()

    def dispatch(self, channel, method, properties, body):
        body = body.decode('utf-8')
        if body == 'quit':
            sys.exit(0)

        print('[x] Received %s' % body)
        self.signals.target.emit(0)

class MainWidget(QObject):

    def __init__(self):
        super(MainWidget, self).__init__()

    def show(self, action):
        try:
            print('[x] Dispatched :' + str(action))
            label = QLabel('Hello World')
            label.show()
        except:
            print(traceback.format_exc())

if __name__ == '__main__':
    app = QApplication([])

    widget = MainWidget()
    pool = QThreadPool()
    listener = MessageListener()
    listener.signals.target.connect(widget.show)
    pool.start(listener)

    app.exec_()

Now, everything works fine except that the label.show line crashes the program, no widget displayed, no message printed.

The client part is listed below, sending quit to quit the server.

import pika

connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='ui')
channel.basic_publish(exchange='', routing_key='ui', body='show label')
connection.close()

My question is, how and why the label.show() shutdown the program without any error? How can I improve the program?

Or is there alternative ways to do the job?

Any suggestions are welcome.

Thank you in advance.

Body:
The problem is that QLabel is a local variable so it will be deleted a moment after the show method is executed. The above should not cause the application to terminate but by default QApplication will be closed if at any time after showing at least one window they all close, in your case QLabel is displayed for a moment and closes, which consequently implies that the application it closes.

So the solution is to make the label a member of the class so that it is not deleted:

# ...
class MainWidget(QObject):
    def __init__(self):
        super(MainWidget, self).__init__()
        self.label = QLabel("Hello World")

    def show(self, action):
        print('[x] Dispatched :' + str(action))
        self.label.show()
# ...

On the other hand, Qt does not return exceptions when some function/method fails in its task, instead it informs us of the success of the execution through a variable, this does it for reasons of efficiency. And that same PyQt inherits so in 99.99% of the python code is not necessary to use try-except.


来源: stackexchange

问:
Why i'm getting [object object] using jQuery?
I have a function there i want to try sum two numbers using variable like given below, but i'm getting [object object] instead of total of sum.

var convenienceCharge = 100;
var totalPgCost = 500;
var subTotalPgCost = 0;

function totalPgCostFunction() {

subTotalPgCost += $('.subTotalPgCost').text(convenienceCharge +  totalPgCost + 18);

alert(subTotalPgCost);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button onclick="totalPgCostFunction();">Click</button></code>```

答:
.text will return a object. that is why you are seeing [object object]

You need to do it like this.

var convenienceCharge = 100;
var totalPgCost = 500;
var subTotalPgCost = 0;

function totalPgCostFunction() {

subTotalPgCost += convenienceCharge +  totalPgCost + 18;

$('.subTotalPgCost').text(subTotalPgCost);
alert(subTotalPgCost);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button onclick="totalPgCostFunction();">Click</button>
<div class="subTotalPgCost"></div></code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a function there i want to try sum two numbers using variable like given below, but i'm getting [object object] instead of total of sum.

var convenienceCharge = 100;
var totalPgCost = 500;
var subTotalPgCost = 0;

function totalPgCostFunction() {

subTotalPgCost += $('.subTotalPgCost').text(convenienceCharge +  totalPgCost + 18);

alert(subTotalPgCost);
}

<button onclick="totalPgCostFunction();">Click</button>

Body:
.text will return a object. that is why you are seeing [object object]

You need to do it like this.

var convenienceCharge = 100;
var totalPgCost = 500;
var subTotalPgCost = 0;

function totalPgCostFunction() {

subTotalPgCost += convenienceCharge +  totalPgCost + 18;

$('.subTotalPgCost').text(subTotalPgCost);
alert(subTotalPgCost);
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button onclick="totalPgCostFunction();">Click</button>
<div class="subTotalPgCost"></div>


问:
Is there an R function for identifying 'n' matches in each row?
I am attempting to aggregate my data to find correlations/patterns, and want to discover how and where data may correlate. Specifically, I want to identify how many times an id (here called 'item') appear together. Is there a way to find how many times each (id) appear together in a row?

This is for a larger data.frame that has already been cleaned and aggregated based on this particular inquiry. In the past, I have tried to apply multiple aggregation, summation and filter functions from packages like 'data.table','dplyr', and 'tidyverse' but cannot quite get what I am looking for.

In section 3(Show some code) I have provided a minimal reproducible example:

```<code>set.seed(1234)
random.people<-c("Bob","Tim","Jackie","Angie","Christopher")
number=sample(12345:12350,2000,replace = T)
item=sample(random.people,2000,replace=T)

sample_data <- data.frame(cbind(number,item), stringsAsFactors = FALSE)
</code>```

Using the examples here,I expected the output to ID all the combinations where names were aggregated to a number and show the n (value) - expecting results to resemble something like:

```<code>Pair       value
Bob, Tim     2
Bob, Jackie  4
Bob, Angie   0
</code>```

This output (what I am hoping to get) would tell me that in the entire df, there are 2 times that Bob and Tim and 4 times that Bob and Jackie both have the same number.

but the actual output is:

```<code>Error: Each row of output must be identified by a unique combination of keys.

Keys are shared for 2000 rows:
* 9, 23, 37, 164, 170, 180, 211...
</code>```

Update: I thought of a..creative(?) solution - but hope someone can help with expedting it. I can locate all the numbers (column1) that are shared between two names using the following:

```<code>x1<-sample_data %>% dplyr::filter(item=="Bob")
x2<-sample_data %>% dplyr::filter(item=="Tim")
Bob<-x1[,1]
Tim<-x2[,1]
Reduce(intersect, list(Bob,Tim))
</code>```

output:

```<code>[1] "12345" "12348" "12350" "12346" "12349" "12347"
</code>```

Like I said, this is very time consuming and would require creating a plethora of vectors and intersecting each(e.g. 1 vector for each name) and multiple combinations.

答:
Here's a base R solution which relies on table -> aggregate and potentially an inefficient way to paste the names together using apply.

```<code>tab_data <-  data.frame(unclass(table(unique(sample_data))))
#table results in columns c(Angie.1, Bob.1, ...) - this makes it look better
names(tab_data) = sort(random.people)

library(network)
plot.network.default(as.network(tab_data))

tab_data$n <- 1

agg_data <- aggregate(n~., data = tab_data, FUN = length)
agg_data$Pair <- apply(agg_data[, -length(agg_data)], 1, function(x) paste(names(x[x!=0]), collapse = ', '))

agg_data[order(agg_data$Pair), c('Pair', 'n') ]

                            Pair   n
1                          Angie 336
3                     Angie, Bob   8
7        Angie, Bob, Christopher   2
11            Angie, Bob, Jackie   1
5             Angie, Christopher  16
9                  Angie, Jackie   9
15                    Angie, Tim  10
2                            Bob 331
6               Bob, Christopher  12
... truncated ...
</code>```

As far as performance, on this relatively small data set, it's around 9x faster than the dplyr solution:

```<code>Unit: milliseconds
           expr     min       lq     mean   median       uq      max neval
  base_solution  9.4795  9.65215 10.80984  9.87625 10.32125  46.8230   100
 dplyr_solution 78.6070 81.72155 86.47891 83.96435 86.40495 200.7784   100
</code>```

Data

```<code>set.seed(1234)
random.people<-c("Bob","Tim","Jackie","Angie","Christopher")
number=sample(12345:22350,2000,replace = T) # I edited ur number here.
item=sample(random.people,2000,replace=T)

sample_data <- data.frame(number,item, n = 1L, stringsAsFactors = FALSE)
</code>```

Body:
I am attempting to aggregate my data to find correlations/patterns, and want to discover how and where data may correlate. Specifically, I want to identify how many times an id (here called 'item') appear together. Is there a way to find how many times each (id) appear together in a row?

This is for a larger data.frame that has already been cleaned and aggregated based on this particular inquiry. In the past, I have tried to apply multiple aggregation, summation and filter functions from packages like 'data.table','dplyr', and 'tidyverse' but cannot quite get what I am looking for.

In section 3(Show some code) I have provided a minimal reproducible example:

set.seed(1234)
random.people<-c("Bob","Tim","Jackie","Angie","Christopher")
number=sample(12345:12350,2000,replace = T)
item=sample(random.people,2000,replace=T)

sample_data <- data.frame(cbind(number,item), stringsAsFactors = FALSE)

Using the examples here,I expected the output to ID all the combinations where names were aggregated to a number and show the n (value) - expecting results to resemble something like:

Pair       value
Bob, Tim     2
Bob, Jackie  4
Bob, Angie   0

This output (what I am hoping to get) would tell me that in the entire df, there are 2 times that Bob and Tim and 4 times that Bob and Jackie both have the same number.

but the actual output is:

Error: Each row of output must be identified by a unique combination of keys.

Keys are shared for 2000 rows:
* 9, 23, 37, 164, 170, 180, 211...

Update: I thought of a..creative(?) solution - but hope someone can help with expedting it. I can locate all the numbers (column1) that are shared between two names using the following:

x1<-sample_data %>% dplyr::filter(item=="Bob")
x2<-sample_data %>% dplyr::filter(item=="Tim")
Bob<-x1[,1]
Tim<-x2[,1]
Reduce(intersect, list(Bob,Tim))

output:

[1] "12345" "12348" "12350" "12346" "12349" "12347"

Like I said, this is very time consuming and would require creating a plethora of vectors and intersecting each(e.g. 1 vector for each name) and multiple combinations.

Body:
Here's a base R solution which relies on table -> aggregate and potentially an inefficient way to paste the names together using apply.

tab_data <-  data.frame(unclass(table(unique(sample_data))))
#table results in columns c(Angie.1, Bob.1, ...) - this makes it look better
names(tab_data) = sort(random.people)

library(network)
plot.network.default(as.network(tab_data))

tab_data$n <- 1

agg_data <- aggregate(n~., data = tab_data, FUN = length)
agg_data$Pair <- apply(agg_data[, -length(agg_data)], 1, function(x) paste(names(x[x!=0]), collapse = ', '))

agg_data[order(agg_data$Pair), c('Pair', 'n') ]

                            Pair   n
1                          Angie 336
3                     Angie, Bob   8
7        Angie, Bob, Christopher   2
11            Angie, Bob, Jackie   1
5             Angie, Christopher  16
9                  Angie, Jackie   9
15                    Angie, Tim  10
2                            Bob 331
6               Bob, Christopher  12
... truncated ...

As far as performance, on this relatively small data set, it's around 9x faster than the dplyr solution:

Unit: milliseconds
           expr     min       lq     mean   median       uq      max neval
  base_solution  9.4795  9.65215 10.80984  9.87625 10.32125  46.8230   100
 dplyr_solution 78.6070 81.72155 86.47891 83.96435 86.40495 200.7784   100

Data

set.seed(1234)
random.people<-c("Bob","Tim","Jackie","Angie","Christopher")
number=sample(12345:22350,2000,replace = T) # I edited ur number here.
item=sample(random.people,2000,replace=T)

sample_data <- data.frame(number,item, n = 1L, stringsAsFactors = FALSE)


问:
Subversion Update Issue
I'm getting the following error when I try to update my repository. Can someone explain what it means?

Command: Update

Error: URL

Error: 'http://mysvn/foo'

Error: of existing directory

Error: 'C:\SVN\MyProj\NinjectModules\Models' does not match

Error: expected URL 'http://mysvn/foo/NinjectModules/Models'

Finished!:

答:
Another reason might be migration from including some files with svn:externals property to actually adding the files to your repository.

That is, when between two updates of your working copy someone does following:

```<code>#svn up removes local copies of external resources when svn:externals is deleted
#so we need a backup
cp -R library/resource /backup
svn propdel 'svn:externals' library
svn up
cp -R /backup/resource library
svn add library/resource
svn commit -m "this will break other working copies, but we have the resource in our repo now"
</code>```

When you try to svn update your wc, you will get following message:

```<code>svn: URL 'svn://path.to/external/resource' of existing directory
'library/resource' does not match expected URL 'svn://my.own.repository/library/resource'
</code>```

In such case the solution is as usual - remove the library directory of the working copy and do svn up to restore it in its current state.

Remeber to back up your local changes somewhere

ContentLicense: CC BY-SA 3.0

Title: Subversion Update Issue

Body:
Another reason might be migration from including some files with svn:externals property to actually adding the files to your repository.

That is, when between two updates of your working copy someone does following:

#svn up removes local copies of external resources when svn:externals is deleted
#so we need a backup
cp -R library/resource /backup
svn propdel 'svn:externals' library
svn up
cp -R /backup/resource library
svn add library/resource
svn commit -m "this will break other working copies, but we have the resource in our repo now"

When you try to svn update your wc, you will get following message:

svn: URL 'svn://path.to/external/resource' of existing directory
'library/resource' does not match expected URL 'svn://my.own.repository/library/resource'

In such case the solution is as usual - remove the library directory of the working copy and do svn up to restore it in its current state.

Remeber to back up your local changes somewhere


问:
How to import a json file with _id (string) as _id (objectId) in mongodb?
I have an array which has multiple objects and objects have _id (string) already set. While I import the file, i want all _id (string) to get imported into _id (objectId).

I have tried manually using "$oid" but it is not a dynamic solution to my problem.

my import statement

```<code>mongoimport --db delivera --collection restaurants --drop --file list.json --jsonArray
</code>```

my example object

```<code>{
"_id":"5a6900fff467be65019a9001",
"date":"2018-01-24T21:56:15.353Z",
"title":"Italian pasta",
"restaurant": "coffee bean",
"__v":0
}
</code>```

答:
You can use the ObjectId() method available in mongoDB shell which returns a new ObjectId value

Your object will look like this

```<code>{
"_id": Object("5a6900fff467be65019a9001"),
"date":"2018-01-24T21:56:15.353Z",
"title":"Italian pasta",
"restaurant": "coffee bean",
"__v":0
}
</code>```

Body:
I have an array which has multiple objects and objects have _id (string) already set. While I import the file, i want all _id (string) to get imported into _id (objectId).

I have tried manually using "$oid" but it is not a dynamic solution to my problem.

my import statement

mongoimport --db delivera --collection restaurants --drop --file list.json --jsonArray

my example object

{
"_id":"5a6900fff467be65019a9001",
"date":"2018-01-24T21:56:15.353Z",
"title":"Italian pasta",
"restaurant": "coffee bean",
"__v":0
}

Body:
You can use the ObjectId() method available in mongoDB shell which returns a new ObjectId value

Your object will look like this

{
"_id": Object("5a6900fff467be65019a9001"),
"date":"2018-01-24T21:56:15.353Z",
"title":"Italian pasta",
"restaurant": "coffee bean",
"__v":0
}


问:
Help with retrieving answers from radio buttons
```<code>$host = 'localhost';
$user = 'root';
$pw = '';
$db = 'pmdb';

mysql_connect($host,$user,$pw);
mysql_select_db($db);

$result = mysql_query("SELECT * FROM Questions WHERE QuizID=1");
$num_rows = mysql_num_rows($result);
while($row = mysql_fetch_assoc($result))
{
    $array[] = $row;
}
for($i=0; $i<=($num_rows-1); $i++)
{
  $title = $array[$i]['Title'];
  $ans1 = $array[$i]['Answer1'];
  $ans2 = $array[$i]['Answer2'];
  $ans3 = $array[$i]['Answer3'];
  $ans4 = $array[$i]['Answer4'];
  echo $title.'<br>';
  echo '<form method="post">';
  echo '<input type="radio" name="ans'.$i.'">'.$ans1.'<br>';
  echo '<input type="radio" name="ans'.$i.'">'.$ans2.'<br>';
  echo '<input type="radio" name="ans'.$i.'">'.$ans3.'<br>';
  echo '<input type="radio" name="ans'.$i.'">'.$ans4.'<br>';
 }
echo '<input type="submit" value="submit" id="submit">';
echo '</form>';
</code>```

I manage to display the question followed by the corresponding choices and at the bottom a submit button.

How would I, on click of the submit button, get the values that the user have chosen for each question that was looped out from the database? ans1, ans2, etc.

This is necessary to compare their answer to the answer key and compute their score.

.help please! Thank you very much and More power!

答:
Assign a value to each of the radio inputs, the updated script could be:

```<code>$host = 'localhost';
$user = 'root';
$pw = '';
$db = 'pmdb';

mysql_connect($host,$user,$pw);
mysql_select_db($db);

$result = mysql_query("SELECT * FROM Questions WHERE QuizID=1");
$num_rows = mysql_num_rows($result);
while($row = mysql_fetch_assoc($result))
{
    $array[] = $row;
}

//Start the form
echo "<form method=\"post\" action=\"path/to/receiving.php\">\n";

for($i=0; $i<=($num_rows-1); $i++)
{
  //Render a question + the answer choices
  echo $array[$i]['Title']."<br />\n";
  for ($j=1;$j<=4;$j++) {
    echo "<input type=\"radio\" name=\"ans$i\" value=\"$j\">".
      $array[$i]['Answer'.$j]."<br />\n";
  }
}

//End the form
echo "<input type=\"submit\" value=\"submit\" id=\"submit\">\n</form>";
</code>```

Now to read the values of the answers from within PHP:

```<code>  echo $_POST["ans1"];
  //The answer given for question 1, will be between
  //  1-4 or null (if they didn't answer
</code>```

Body:
$host = 'localhost';
$user = 'root';
$pw = '';
$db = 'pmdb';

mysql_connect($host,$user,$pw);
mysql_select_db($db);

$result = mysql_query("SELECT * FROM Questions WHERE QuizID=1");
$num_rows = mysql_num_rows($result);
while($row = mysql_fetch_assoc($result))
{
    $array[] = $row;
}
for($i=0; $i<=($num_rows-1); $i++)
{
  $title = $array[$i]['Title'];
  $ans1 = $array[$i]['Answer1'];
  $ans2 = $array[$i]['Answer2'];
  $ans3 = $array[$i]['Answer3'];
  $ans4 = $array[$i]['Answer4'];
  echo $title.'
';
  echo '<form method="post">';
  echo '<input type="radio" name="ans'.$i.'">'.$ans1.'
';
  echo '<input type="radio" name="ans'.$i.'">'.$ans2.'
';
  echo '<input type="radio" name="ans'.$i.'">'.$ans3.'
';
  echo '<input type="radio" name="ans'.$i.'">'.$ans4.'
';
 }
echo '<input type="submit" value="submit" id="submit">';
echo '</form>';

I manage to display the question followed by the corresponding choices and at the bottom a submit button.

How would I, on click of the submit button, get the values that the user have chosen for each question that was looped out from the database? ans1, ans2, etc.

This is necessary to compare their answer to the answer key and compute their score.

.help please! Thank you very much and More power!

Body:
Assign a value to each of the radio inputs, the updated script could be:

$host = 'localhost';
$user = 'root';
$pw = '';
$db = 'pmdb';

mysql_connect($host,$user,$pw);
mysql_select_db($db);

$result = mysql_query("SELECT * FROM Questions WHERE QuizID=1");
$num_rows = mysql_num_rows($result);
while($row = mysql_fetch_assoc($result))
{
    $array[] = $row;
}

//Start the form
echo "<form method=\"post\" action=\"path/to/receiving.php\">\n";

for($i=0; $i<=($num_rows-1); $i++)
{
  //Render a question + the answer choices
  echo $array[$i]['Title']."<br />\n";
  for ($j=1;$j<=4;$j++) {
    echo "<input type=\"radio\" name=\"ans$i\" value=\"$j\">".
      $array[$i]['Answer'.$j]."<br />\n";
  }
}

//End the form
echo "<input type=\"submit\" value=\"submit\" id=\"submit\">\n</form>";

Now to read the values of the answers from within PHP:

  echo $_POST["ans1"];
  //The answer given for question 1, will be between
  //  1-4 or null (if they didn't answer


答:
The issue is because when you call the setter of text() it returns a jQuery object, hence the output you see.

To make this work you need to split the calculation and text() logic, like this:

var convenienceCharge = 100;
var totalPgCost = 500;
var subTotalPgCost = 0;

$(function() {
  $('button').click(function() {
    subTotalPgCost += convenienceCharge + totalPgCost + 18;
    $('.subTotalPgCost').text(subTotalPgCost);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button>Click</button>
<div class="subTotalPgCost"></div></code>```

Also note the use of an unobtrusive event handler in this example instead of the outdated on* attribute.

Title: Why i'm getting [object object] using jQuery?

Body:
The issue is because when you call the setter of text() it returns a jQuery object, hence the output you see.

To make this work you need to split the calculation and text() logic, like this:

var convenienceCharge = 100;
var totalPgCost = 500;
var subTotalPgCost = 0;

$(function() {
  $('button').click(function() {
    subTotalPgCost += convenienceCharge + totalPgCost + 18;
    $('.subTotalPgCost').text(subTotalPgCost);
  });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button>Click</button>
<div class="subTotalPgCost"></div>

Also note the use of an unobtrusive event handler in this example instead of the outdated on* attribute.


问:
Get contents of a particular row
I want to locate 'td' where text is 'xyz' so that I can find other attributes in the row. I only have 'xyz' with me and want to get other elements in that row.

```<code>.
.
.

<tr>
    <td>
        <a>xyz</a>
    </td>
    <td>address</td>
    <td>phone number</td>
</tr>

.
.
.
</code>```

I can get 'xyz' easily by using

```<code>required = soup.find('a', text = 'xyz')
print(required[0].text)
</code>```

but I'm not able to locate 'td' so that I can use find_next_siblings() to get other columns.

Expected output:

```<code>xyz
address
phone number
</code>```

答:
You can use xpath. find_elements_by_xpath().</p>

```<code>https://www.softwaretestingmaterial.com/how-to-locate-element-by-xpath-locator/
</code>```

Title: Get contents of a particular row

Body:
I want to locate 'td' where text is 'xyz' so that I can find other attributes in the row. I only have 'xyz' with me and want to get other elements in that row.

.
.
.

        xyz

    address
    phone number

.
.
.

I can get 'xyz' easily by using

required = soup.find('a', text = 'xyz')
print(required[0].text)

but I'm not able to locate 'td' so that I can use find_next_siblings() to get other columns.

Expected output:

xyz
address
phone number

Body:
You can use xpath. find_elements_by_xpath().

https://www.softwaretestingmaterial.com/how-to-locate-element-by-xpath-locator/


问:
How to generate oauth token for webapi without using client id and client secret
I have deployed one webapi into azure. After that I have register my API into Azure AD.

I got my API client-id and client-secret, now i just want to test my API not like
3rd application will access it so what will be recourse id in this case.

I have used oauth for authentication into that webapi.

I want to test that webapi so into POSTMAN i used this url to generate oauth token

which i will pass as header Authentication bearer token.

step 1 -
https://login.microsoftonline.com/{{OAuth_Tenant}}/oauth2/token

in header -

```<code>grant_type:client_credentials
client_id:{{client_id}}           // i have my API client-id
client_secret:{{client_secret}}   // i have my API client-secret
resource:{{resource}}             // i have my API client-id
</code>```

when i generate token using above values and send that bearer token it fail error unauthorized.

答:
You need to register an app in Azure Active Directory to acquire access tokens.

Register an app there, and you can find the client id/application id there.
Then you can create a key for the app, that's your client secret.
Finally the resource should be the client id or app id URI for your API's app registration in Azure AD.

To implement this according to best practices, you'll also want to look into defining app permissions for your API, so you can then assign privileges to apps to call your API.

Body:
I have deployed one webapi into azure. After that I have register my API into Azure AD.

I got my API client-id and client-secret, now i just want to test my API not like
3rd application will access it so what will be recourse id in this case.

I have used oauth for authentication into that webapi.

I want to test that webapi so into POSTMAN i used this url to generate oauth token

which i will pass as header Authentication bearer token.

step 1 -
https://login.microsoftonline.com/{{OAuth_Tenant}}/oauth2/token

in header -

grant_type:client_credentials
client_id:{{client_id}}           // i have my API client-id
client_secret:{{client_secret}}   // i have my API client-secret
resource:{{resource}}             // i have my API client-id

when i generate token using above values and send that bearer token it fail error unauthorized.


问:
How to count everything but letters at end of a string
I have a random string and need to know the number of non-letter / non-number characters at the end of it.

For example:

"Some text." should result in 1

"More text 123 !.?" should result in 4 (blanks included)

"Even more text 123" should result in 0

How can I do that?

答:
It's easy with LINQ:

```<code>using System.Linq;
</code>```

This function also handles null strings and returns -1 for them.

```<code>    public static int CountNonLettersAtEnd(string input)
        => input?.Reverse().TakeWhile(c => !char.IsLetterOrDigit(c)).Count() ?? -1;
</code>```

Body:
It's easy with LINQ:

using System.Linq;

This function also handles null strings and returns -1 for them.

    public static int CountNonLettersAtEnd(string input)
        => input?.Reverse().TakeWhile(c => !char.IsLetterOrDigit(c)).Count() ?? -1;


问:
Oracle Query [need subquery?]
assuming I have the following table:

```<code>NUM  TYPE  STAT   ERR
123   10      6    62
123   10      6    62
123   10      6    62
123   17      4     0
321   10      6    62
321   10      6    62
</code>```

I'm currently using the following query:

```<code>select MIN(NUM) as NUMBER
     , MIN(STAT) as STATUS
     , MIN(ERR) as ERROR
     , MIN(retry) as RETRY
 from TABLE_TB
where ERR=62
group by NUM
having count(ERR) > 1;
</code>```

The output will be:

```<code>NUM  TYPE  STAT   ERR  RETRY
123   10      6    62      3
321   10      6    62      2
</code>```

That's ok, but what I need is that the query will output only NUM WITH ERR=62 but also with ERR = 0 excluding those who have ERR=62 but without ERR=0. Taking the first table as example, the query should output

```<code>NUM  TYPE  STAT   ERR  RETRY
123   10      6    62      3
</code>```

This because NUM 123 has ERR=62 (3 occurrency) but also ERR=0. So, NUM 321 will be excluded because even if has ERR=62, it doesn't have ERR=0.

Hope is cliear :)

Thank you very much.
Lucas

答:
Or perhaps you can try this way, simple and sweet...

```select MIN(NUM) as NUMBER
     , MIN(STAT) as STATUS
     , MAX(ERR) as ERROR
     , Count(*) as RETRY
 from TestTable
where ERR IN (62 ,0)
group by NUM
having count(ERR) > 1 AND MIN(ERR)=0;```

Title: Oracle Query [need subquery?]

Body:
assuming I have the following table:

NUM  TYPE  STAT   ERR
123   10      6    62
123   10      6    62
123   10      6    62
123   17      4     0
321   10      6    62
321   10      6    62

I'm currently using the following query:

select MIN(NUM) as NUMBER
     , MIN(STAT) as STATUS
     , MIN(ERR) as ERROR
     , MIN(retry) as RETRY
 from TABLE_TB
where ERR=62
group by NUM
having count(ERR) > 1;

The output will be:

NUM  TYPE  STAT   ERR  RETRY
123   10      6    62      3
321   10      6    62      2

That's ok, but what I need is that the query will output only NUM WITH ERR=62 but also with ERR = 0 excluding those who have ERR=62 but without ERR=0. Taking the first table as example, the query should output

NUM  TYPE  STAT   ERR  RETRY
123   10      6    62      3

This because NUM 123 has ERR=62 (3 occurrency) but also ERR=0. So, NUM 321 will be excluded because even if has ERR=62, it doesn't have ERR=0.

Hope is cliear :)

Thank you very much.
Lucas

Body:
Or perhaps you can try this way, simple and sweet...

select MIN(NUM) as NUMBER
     , MIN(STAT) as STATUS
     , MAX(ERR) as ERROR
     , Count(*) as RETRY
 from TestTable
where ERR IN (62 ,0)
group by NUM
having count(ERR) > 1 AND MIN(ERR)=0;


问:
My question is about addition of an array of different wrapper classes through java generics
```<code>public static void doProcess(){
   Integer [] intArray = {2,5,3,8,9};
   returnArray(intArray);
   //Expected output:  27 (sum of all number)
   String[]  strArray =  {"Jack", "Daniel", "Richel"};
   returnArray(strArray);
   //Expected output:  Jack Daniel Richel
   Character[]  charArray = {'A', 'X', 'E'};
   returnArray(charArray);
   //Expected output:  AXE
}
</code>```

I have the above code and the method below which need to complete.

```<code>private static <E> *** returnArray(E[] value) {
    for(E ele : value) {
        //code for expected output
    }
    //return Expected output
}
</code>```

I need to fill above method as well as fill the return type which is here shown as ***.
I can't use separate method or introduce any new method.

答:
Just adding to @Lino's answer to suggest a more generic approach: I will assume you want to sum up numbers (be it integers, floats or whatever) and concat anything else (strings, chars, even random objects like Duration or Instant). It's just that characters will be squashed together, while strings (or anything else, for that matter) will be joined with a space separator.

You can return Object or something a bit narrower that fits both numbers and strings (like Serializable or Comparable<?>); this is hardly useful, but keeps you from returning really random stuff.

Alternatively, you can decide to always return String and just return the sum as a string as well (for numbers).

The actual implementation can look pretty neat if you use Java8 streams:

```<code>// the `E` generic type brings you nothing, as you can't make use of it at compile time,
// so you can simply drop it and go with a mere `Object[]` array, as per @Lino
public static <E> Serializable returnArray(E[] values) {

    // exclude null values if any (note that `E` proves itself useless already):
    final Stream<?> stream = Stream.of(values).filter(Objects::nonNull);

    if (values instanceof Number[]) {
        // you can use mapToDouble and doubleValue, for a more accurate sum
        return stream.map(Number.class::cast).mapToInt(Number::intValue).sum();
    } else {
        // squash characters, but use a space separator for anything else
        final String separator = (values instanceof Character[]) ? "" : " ";
        return stream.map(Object::toString).collect(Collectors.joining(separator));
    }
}
</code>```

Body:
public static void doProcess(){
   Integer [] intArray = {2,5,3,8,9};
   returnArray(intArray);
   //Expected output:  27 (sum of all number)
   String[]  strArray =  {"Jack", "Daniel", "Richel"};
   returnArray(strArray);
   //Expected output:  Jack Daniel Richel
   Character[]  charArray = {'A', 'X', 'E'};
   returnArray(charArray);
   //Expected output:  AXE
}

I have the above code and the method below which need to complete.

private static <E> *** returnArray(E[] value) {
    for(E ele : value) {
        //code for expected output
    }
    //return Expected output
}

I need to fill above method as well as fill the return type which is here shown as ***.
I can't use separate method or introduce any new method.

Body:
Just adding to @Lino's answer to suggest a more generic approach: I will assume you want to sum up numbers (be it integers, floats or whatever) and concat anything else (strings, chars, even random objects like Duration or Instant). It's just that characters will be squashed together, while strings (or anything else, for that matter) will be joined with a space separator.

You can return Object or something a bit narrower that fits both numbers and strings (like Serializable or Comparable<?>); this is hardly useful, but keeps you from returning really random stuff.

Alternatively, you can decide to always return String and just return the sum as a string as well (for numbers).

The actual implementation can look pretty neat if you use Java8 streams:

// the `E` generic type brings you nothing, as you can't make use of it at compile time,
// so you can simply drop it and go with a mere `Object[]` array, as per @Lino
public static <E> Serializable returnArray(E[] values) {

    // exclude null values if any (note that `E` proves itself useless already):
    final Stream<?> stream = Stream.of(values).filter(Objects::nonNull);

    if (values instanceof Number[]) {
        // you can use mapToDouble and doubleValue, for a more accurate sum
        return stream.map(Number.class::cast).mapToInt(Number::intValue).sum();
    } else {
        // squash characters, but use a space separator for anything else
        final String separator = (values instanceof Character[]) ? "" : " ";
        return stream.map(Object::toString).collect(Collectors.joining(separator));
    }
}


问:
C#: How to add an attributes to an object at run-time?
As an entity class, I want to add an attributes at run-time, how should I do?</p>

答:
What needs to see the attributes? If it is things like data-binding etc, TypeDescriptor should work:

```<code>TypeDescriptor.AddAttributes(type, attribs);
TypeDescriptor.AddAttributes(instance, attribs);
</code>```

This only affects System.ComponentModel usage (not direct reflection), but that is often enough - for example, you can associate a TypeConverter via the above.

If by "attributes" you mean "properties", then (again, as far as data-binding is concerned) TypeDescriptor also has potential there - but it is non-trivial; you need to either implement ICustomTypeDescriptor on the object, or to write a CustomTypeDescriptor for the type - and in either case, you need to write your own PropertyDescriptor implementation (often talking to a per-instance dictionary etc). This will get used by anything that uses:

```<code>// only works if you use TypeDescriptionProvider
PropertyDescriptorCollection typeProps = TypeDescriptor.GetProperties(type);
// works via TypeDescriptionProvider or ICustomTypeDescriptor
PropertyDescriptorCollection objProps = TypeDescriptor.GetProperties(obj);
</code>```

Again, this covers a wide range of data-binding and similar scenarios. For an example of this, see here - it is far from trivial, however. The example usage (from the link) adds two properties at runtime:

```<code>Bag.AddProperty<int>("TestProp", new DefaultValueAttribute(5));
Bag.AddProperty<string>("Name");
</code>```

LastEditorDisplayName: Samuel

Body:
What needs to see the attributes? If it is things like data-binding etc, TypeDescriptor should work:

TypeDescriptor.AddAttributes(type, attribs);
TypeDescriptor.AddAttributes(instance, attribs);

This only affects System.ComponentModel usage (not direct reflection), but that is often enough - for example, you can associate a TypeConverter via the above.

If by "attributes" you mean "properties", then (again, as far as data-binding is concerned) TypeDescriptor also has potential there - but it is non-trivial; you need to either implement ICustomTypeDescriptor on the object, or to write a CustomTypeDescriptor for the type - and in either case, you need to write your own PropertyDescriptor implementation (often talking to a per-instance dictionary etc). This will get used by anything that uses:

// only works if you use TypeDescriptionProvider
PropertyDescriptorCollection typeProps = TypeDescriptor.GetProperties(type);
// works via TypeDescriptionProvider or ICustomTypeDescriptor
PropertyDescriptorCollection objProps = TypeDescriptor.GetProperties(obj);

Again, this covers a wide range of data-binding and similar scenarios. For an example of this, see here - it is far from trivial, however. The example usage (from the link) adds two properties at runtime:

Bag.AddProperty<int>("TestProp", new DefaultValueAttribute(5));
Bag.AddProperty<string>("Name");

OwnerDisplayName: Marc Gravell

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Marc Gravell


问:
Selenium RC and PHP for beginners
I am running a ubuntu server with apache/php/mysql. I want to use selenium on one of my php projects. Basically, I want a setup where I can more or less copy paste code from the Firefox Selenium IDE (format set to php) into my php project, like this:

```<code><?php

require_once 'PHPUnit/Extensions/SeleniumTestCase.php';

class Example extends PHPUnit_Extensions_SeleniumTestCase
{
  protected function setUp()
  {
    $this->setBrowser("*chrome");
    $this->setBrowserUrl("http://www.google.com/");
  }

  public function testMyTestCase()
  {
    $this->type("q", "stack overflow");
    $this->click("link=2");
    $this->waitForPageToLoad("30000");
    $this->click("btnG");
    $this->waitForPageToLoad("30000");
    $this->type("q", "stack overflow php");
    $this->click("btnG");
    $this->waitForPageToLoad("30000");
  }
}
?>
</code>```

I have tried to figure out how to do this in PHP using Selenium RC, but the documentation is confusing and outdated.

I would be very grateful for instructions for beginners on how to get started with PHP and Selenium RC.

Thank you very much.

EDIT:

Thanks for the feedback. I have got Selenium up and running on Ubuntu/firefox and it is obvious that this is not what I am looking for. The fact that it runs a java server and is dependent on a full blown browser makes it anything than lightweight.

If anyone knows a similar solution where you can just load a php library to interact with dom/html, please tell me.

答:
Try simpletest webtester:

http://www.simpletest.org/en/web_tester_documentation.html

Its a very simple library which fits your requirements of "similar solution where you can just load a php library to interact with dom/html"

Title: Selenium RC and PHP for beginners

Body:
I am running a ubuntu server with apache/php/mysql. I want to use selenium on one of my php projects. Basically, I want a setup where I can more or less copy paste code from the Firefox Selenium IDE (format set to php) into my php project, like this:

<?php

require_once 'PHPUnit/Extensions/SeleniumTestCase.php';

class Example extends PHPUnit_Extensions_SeleniumTestCase
{
  protected function setUp()
  {
    $this->setBrowser("*chrome");
    $this->setBrowserUrl("http://www.google.com/");
  }

  public function testMyTestCase()
  {
    $this->type("q", "stack overflow");
    $this->click("link=2");
    $this->waitForPageToLoad("30000");
    $this->click("btnG");
    $this->waitForPageToLoad("30000");
    $this->type("q", "stack overflow php");
    $this->click("btnG");
    $this->waitForPageToLoad("30000");
  }
}
?>

I have tried to figure out how to do this in PHP using Selenium RC, but the documentation is confusing and outdated.

I would be very grateful for instructions for beginners on how to get started with PHP and Selenium RC.

Thank you very much.

EDIT:

Thanks for the feedback. I have got Selenium up and running on Ubuntu/firefox and it is obvious that this is not what I am looking for. The fact that it runs a java server and is dependent on a full blown browser makes it anything than lightweight.

If anyone knows a similar solution where you can just load a php library to interact with dom/html, please tell me.


问:
Scrollview not working inside linearlayout
I want to use scrollview inside linearlayout and want to scroll particular this layout but it is not working.this is my code

```<code>  <?xml version="1.0" encoding="utf-8"?>

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:scrollbars="vertical">

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

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

    <LinearLayout
        android:id="@+id/ll_client_main"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/dp15"
        android:background="@drawable/rounded_layout_white"
        android:orientation="horizontal"
        android:padding="@dimen/dp5"
        android:weightSum="1">

        <ImageView
            android:layout_width="@dimen/dp0"
            android:layout_height="match_parent"
            android:layout_weight="0.1"
            android:src="@drawable/img_user_icon" />

        <TextView
            android:id="@+id/tv_client_name"
            android:layout_width="@dimen/dp0"
            android:layout_height="match_parent"
            android:layout_weight="0.9"
            android:gravity="left|center"
            android:padding="@dimen/dp10"
            android:text=""
            android:textColor="@color/colorLightBlue"
            android:textSize="@dimen/dp12"
            android:textStyle="bold"

            />
    </LinearLayout>

    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dp50"
        android:theme="@style/AppTheme.WhiteAccent"
        android:visibility="visible" />

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

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

            <ListView
                android:id="@+id/lst_client_scheme"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="@dimen/dp10"
                android:layout_marginTop="@dimen/dp20"
                android:layout_marginRight="@dimen/dp10"
                android:background="@color/colorGray"
                android:dividerHeight="0sp"
                android:scrollbars="vertical"
                android:visibility="visible"></ListView>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="@dimen/dp300"
                android:layout_marginLeft="@dimen/dp10"
                android:layout_marginTop="@dimen/dp10"
                android:layout_marginRight="@dimen/dp10"
                android:background="@android:color/darker_gray"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/tv_summary_date"
                    android:layout_width="match_parent"
                    android:layout_height="@dimen/dp25"
                    android:layout_marginTop="@dimen/dp20"
                    android:background="@android:color/darker_gray"
                    android:gravity="center"
                    android:text=""
                    android:textColor="@color/colorWhite"
                    android:textSize="@dimen/dp12" />

                <View
                    android:layout_width="match_parent"
                    android:layout_height="@dimen/dp2"
                    android:background="@color/colorWhite" />

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="horizontal"
                    android:weightSum="1">

                    <LinearLayout
                        android:layout_width="@dimen/dp0"
                        android:layout_height="match_parent"
                        android:layout_weight="0.5"
                        android:gravity="center"
                        android:orientation="vertical"
                        android:weightSum="1">

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

                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp30"
                                android:gravity="right"
                                android:text="Total Amount Invested"
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <TextView
                                android:id="@+id/tv_total_invst_amt"
                                android:layout_width="wrap_content"
                                android:layout_height="@dimen/dp40"
                                android:layout_marginTop="@dimen/dp5"

                              android:background="@drawable/corner_border"
                                android:gravity="center|right"
                                android:padding="@dimen/dp5"
                                android:text="9,857.51"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />
                        </LinearLayout>

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_marginTop="@dimen/dp5"
                            android:gravity="right"
                            android:orientation="vertical">

                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp30"
                                android:gravity="right"
                                android:text="Total Current Amount"
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <TextView
                                android:id="@+id/tv_total_Curr_val"
                                android:layout_width="wrap_content"
                                android:layout_height="@dimen/dp40"
                                android:layout_marginTop="@dimen/dp5"

                              android:background="@drawable/corner_border"
                                android:gravity="center|right"
                                android:padding="@dimen/dp5"
                                android:text="9,857.51"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />
                        </LinearLayout>

                    </LinearLayout>

                    <View
                        android:layout_width="@dimen/dp2"
                        android:layout_height="match_parent"
                        android:layout_marginLeft="@dimen/dp3"
                        android:background="@color/colorWhite" />

                    <LinearLayout
                        android:layout_width="@dimen/dp0"
                        android:layout_height="match_parent"
                        android:layout_weight="0.5"
                        android:gravity="top"
                        android:orientation="vertical"
                        android:weightSum="5">

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="@dimen/dp0"
                            android:layout_weight="1"
                            android:orientation="vertical"
                            android:weightSum="1">

                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp0"
                                android:layout_weight="0.5"
                                android:gravity="right|center"
                                android:padding="@dimen/dp5"
                                android:text="Total Gain/Loss ST"
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <TextView
                                android:id="@+id/tv_total_gl_St"
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp0"
                                android:layout_weight="0.5"
                                android:gravity="center|right"
                                android:padding="@dimen/dp5"
                                android:text=""
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <View
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp2"
                                android:background="@color/colorWhite" />
                        </LinearLayout>

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="@dimen/dp0"
                            android:layout_weight="1"
                            android:orientation="vertical"
                            android:weightSum="1">

                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp0"
                                android:layout_weight="0.5"
                                android:gravity="right|center"
                                android:padding="@dimen/dp5"
                                android:text="Total Gain/Loss LT"
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <TextView
                                android:id="@+id/tv_total_gl_lt"
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp0"
                                android:layout_weight="0.5"
                                android:gravity="center|right"
                                android:padding="@dimen/dp5"
                                android:text=""
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <View
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp2"
                                android:background="@color/colorWhite" />
                        </LinearLayout>

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="@dimen/dp0"
                            android:layout_weight="1"
                            android:orientation="vertical"
                            android:weightSum="1">

                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp0"
                                android:layout_weight="0.5"
                                android:gravity="right|center"
                                android:padding="@dimen/dp5"
                                android:text="Total Dividend Reinvest"
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <TextView
                                android:id="@+id/tv_total_div_amt"
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp0"
                                android:layout_weight="0.5"
                                android:gravity="center|right"
                                android:padding="@dimen/dp5"
                                android:text=""
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <View
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp2"
                                android:background="@color/colorWhite" />
                        </LinearLayout>

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="@dimen/dp0"
                            android:layout_weight="1"
                            android:orientation="vertical"
                            android:weightSum="1">

                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp0"
                                android:layout_weight="0.5"
                                android:gravity="right|center"
                                android:padding="@dimen/dp5"
                                android:text="Total Ret ABS"
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <TextView
                                android:id="@+id/tv_ret_abs"
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp0"
                                android:layout_weight="0.5"
                                android:gravity="center|right"
                                android:padding="@dimen/dp5"
                                android:text=""
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <View
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp2"
                                android:background="@color/colorWhite" />
                        </LinearLayout>

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="@dimen/dp0"
                            android:layout_weight="1"
                            android:orientation="vertical"
                            android:weightSum="1">

                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp0"
                                android:layout_weight="0.5"
                                android:gravity="right|center"
                                android:padding="@dimen/dp5"
                                android:text="Total Weg. CAGR"
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <TextView
                                android:id="@+id/tv_weg_cagr"
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp0"
                                android:layout_weight="0.5"
                                android:gravity="center|right"
                                android:padding="@dimen/dp5"
                                android:text=""
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                        </LinearLayout>
                    </LinearLayout>

                </LinearLayout>
            </LinearLayout>

        </LinearLayout>
    </android.support.v4.widget.NestedScrollView>
  </LinearLayout>
 </ScrollView>
</code>```

How I modify this code to scroll layout? I want to scroll particular layout inside the main linear layout.is it fine? guide me over this.is this code is ok?
How I use scroll view inside the linear layout.

答:
Use NestedScrollView inside another scrolling view</p>

```<code> <android.support.v4.widget.NestedScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">

   </android.support.v4.widget.NestedScrollView>
</code>```

Body:
I want to use scrollview inside linearlayout and want to scroll particular this layout but it is not working.this is my code

  <?xml version="1.0" encoding="utf-8"?>

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:scrollbars="vertical">

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

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

    <LinearLayout
        android:id="@+id/ll_client_main"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/dp15"
        android:background="@drawable/rounded_layout_white"
        android:orientation="horizontal"
        android:padding="@dimen/dp5"
        android:weightSum="1">

        <ImageView
            android:layout_width="@dimen/dp0"
            android:layout_height="match_parent"
            android:layout_weight="0.1"
            android:src="@drawable/img_user_icon" />

        <TextView
            android:id="@+id/tv_client_name"
            android:layout_width="@dimen/dp0"
            android:layout_height="match_parent"
            android:layout_weight="0.9"
            android:gravity="left|center"
            android:padding="@dimen/dp10"
            android:text=""
            android:textColor="@color/colorLightBlue"
            android:textSize="@dimen/dp12"
            android:textStyle="bold"

            />
    </LinearLayout>

    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dp50"
        android:theme="@style/AppTheme.WhiteAccent"
        android:visibility="visible" />

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

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

            <ListView
                android:id="@+id/lst_client_scheme"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="@dimen/dp10"
                android:layout_marginTop="@dimen/dp20"
                android:layout_marginRight="@dimen/dp10"
                android:background="@color/colorGray"
                android:dividerHeight="0sp"
                android:scrollbars="vertical"
                android:visibility="visible"></ListView>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="@dimen/dp300"
                android:layout_marginLeft="@dimen/dp10"
                android:layout_marginTop="@dimen/dp10"
                android:layout_marginRight="@dimen/dp10"
                android:background="@android:color/darker_gray"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/tv_summary_date"
                    android:layout_width="match_parent"
                    android:layout_height="@dimen/dp25"
                    android:layout_marginTop="@dimen/dp20"
                    android:background="@android:color/darker_gray"
                    android:gravity="center"
                    android:text=""
                    android:textColor="@color/colorWhite"
                    android:textSize="@dimen/dp12" />

                <View
                    android:layout_width="match_parent"
                    android:layout_height="@dimen/dp2"
                    android:background="@color/colorWhite" />

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="horizontal"
                    android:weightSum="1">

                    <LinearLayout
                        android:layout_width="@dimen/dp0"
                        android:layout_height="match_parent"
                        android:layout_weight="0.5"
                        android:gravity="center"
                        android:orientation="vertical"
                        android:weightSum="1">

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

                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp30"
                                android:gravity="right"
                                android:text="Total Amount Invested"
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <TextView
                                android:id="@+id/tv_total_invst_amt"
                                android:layout_width="wrap_content"
                                android:layout_height="@dimen/dp40"
                                android:layout_marginTop="@dimen/dp5"

                              android:background="@drawable/corner_border"
                                android:gravity="center|right"
                                android:padding="@dimen/dp5"
                                android:text="9,857.51"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />
                        </LinearLayout>

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_marginTop="@dimen/dp5"
                            android:gravity="right"
                            android:orientation="vertical">

                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp30"
                                android:gravity="right"
                                android:text="Total Current Amount"
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <TextView
                                android:id="@+id/tv_total_Curr_val"
                                android:layout_width="wrap_content"
                                android:layout_height="@dimen/dp40"
                                android:layout_marginTop="@dimen/dp5"

                              android:background="@drawable/corner_border"
                                android:gravity="center|right"
                                android:padding="@dimen/dp5"
                                android:text="9,857.51"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />
                        </LinearLayout>

                    </LinearLayout>

                    <View
                        android:layout_width="@dimen/dp2"
                        android:layout_height="match_parent"
                        android:layout_marginLeft="@dimen/dp3"
                        android:background="@color/colorWhite" />

                    <LinearLayout
                        android:layout_width="@dimen/dp0"
                        android:layout_height="match_parent"
                        android:layout_weight="0.5"
                        android:gravity="top"
                        android:orientation="vertical"
                        android:weightSum="5">

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="@dimen/dp0"
                            android:layout_weight="1"
                            android:orientation="vertical"
                            android:weightSum="1">

                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp0"
                                android:layout_weight="0.5"
                                android:gravity="right|center"
                                android:padding="@dimen/dp5"
                                android:text="Total Gain/Loss ST"
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <TextView
                                android:id="@+id/tv_total_gl_St"
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp0"
                                android:layout_weight="0.5"
                                android:gravity="center|right"
                                android:padding="@dimen/dp5"
                                android:text=""
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <View
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp2"
                                android:background="@color/colorWhite" />
                        </LinearLayout>

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="@dimen/dp0"
                            android:layout_weight="1"
                            android:orientation="vertical"
                            android:weightSum="1">

                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp0"
                                android:layout_weight="0.5"
                                android:gravity="right|center"
                                android:padding="@dimen/dp5"
                                android:text="Total Gain/Loss LT"
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <TextView
                                android:id="@+id/tv_total_gl_lt"
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp0"
                                android:layout_weight="0.5"
                                android:gravity="center|right"
                                android:padding="@dimen/dp5"
                                android:text=""
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <View
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp2"
                                android:background="@color/colorWhite" />
                        </LinearLayout>

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="@dimen/dp0"
                            android:layout_weight="1"
                            android:orientation="vertical"
                            android:weightSum="1">

                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp0"
                                android:layout_weight="0.5"
                                android:gravity="right|center"
                                android:padding="@dimen/dp5"
                                android:text="Total Dividend Reinvest"
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <TextView
                                android:id="@+id/tv_total_div_amt"
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp0"
                                android:layout_weight="0.5"
                                android:gravity="center|right"
                                android:padding="@dimen/dp5"
                                android:text=""
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <View
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp2"
                                android:background="@color/colorWhite" />
                        </LinearLayout>

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="@dimen/dp0"
                            android:layout_weight="1"
                            android:orientation="vertical"
                            android:weightSum="1">

                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp0"
                                android:layout_weight="0.5"
                                android:gravity="right|center"
                                android:padding="@dimen/dp5"
                                android:text="Total Ret ABS"
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <TextView
                                android:id="@+id/tv_ret_abs"
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp0"
                                android:layout_weight="0.5"
                                android:gravity="center|right"
                                android:padding="@dimen/dp5"
                                android:text=""
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <View
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp2"
                                android:background="@color/colorWhite" />
                        </LinearLayout>

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="@dimen/dp0"
                            android:layout_weight="1"
                            android:orientation="vertical"
                            android:weightSum="1">

                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp0"
                                android:layout_weight="0.5"
                                android:gravity="right|center"
                                android:padding="@dimen/dp5"
                                android:text="Total Weg. CAGR"
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <TextView
                                android:id="@+id/tv_weg_cagr"
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp0"
                                android:layout_weight="0.5"
                                android:gravity="center|right"
                                android:padding="@dimen/dp5"
                                android:text=""
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                        </LinearLayout>
                    </LinearLayout>

                </LinearLayout>
            </LinearLayout>

        </LinearLayout>
    </android.support.v4.widget.NestedScrollView>
  </LinearLayout>
 </ScrollView>

How I modify this code to scroll layout? I want to scroll particular layout inside the main linear layout.is it fine? guide me over this.is this code is ok?
How I use scroll view inside the linear layout.

Body:
Use NestedScrollView inside another scrolling view

 <android.support.v4.widget.NestedScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">

   </android.support.v4.widget.NestedScrollView>


问:
Alamofire get request
I am trying to hit an API with the below alamofire request with headers passed as parameters. but it's not happening</p>

```<code>let url = "http://192.168.1.42/api/v1/userConfig/8b5dbf7d9bdd40d29472be44efa9b7d3"
let secondTok: String = String(Token.get())

let bear = "Bearer " + secondTok

let param = ["Content-Type" : "application/json","Accept" : "application/json", "Authorization" : bear]

Alamofire.request(url, method: .get , parameters: param , encoding: JSONEncoding.default).responseJSON { response in
</code>```

答:
Alamofire Using get Method</p>

```<code>Alamofire.request("http://api.androidhive.info/contacts/", method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) -> Void in
            switch response.result {
            case .success:
                if let data = response.result.value as? Dictionary<String, AnyObject> {
                    self.array = data["contacts"] as! Array<Dictionary<String, AnyObject>>
                }
//                self.data = response.result.value as? [String, AnyObject]
                break
            case .failure:
                print("Error")
            }
            if self.array.count > 0 {
                self.tableview.reloadData()
            }

        }
</code>```

Title: Alamofire get request

Body:
I am trying to hit an API with the below alamofire request with headers passed as parameters. but it's not happening

let url = "http://192.168.1.42/api/v1/userConfig/8b5dbf7d9bdd40d29472be44efa9b7d3"
let secondTok: String = String(Token.get())

let bear = "Bearer " + secondTok

let param = ["Content-Type" : "application/json","Accept" : "application/json", "Authorization" : bear]

Alamofire.request(url, method: .get , parameters: param , encoding: JSONEncoding.default).responseJSON { response in

Body:
Alamofire Using get Method

Alamofire.request("http://api.androidhive.info/contacts/", method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) -> Void in
            switch response.result {
            case .success:
                if let data = response.result.value as? Dictionary<String, AnyObject> {
                    self.array = data["contacts"] as! Array<Dictionary<String, AnyObject>>
                }
//                self.data = response.result.value as? [String, AnyObject]
                break
            case .failure:
                print("Error")
            }
            if self.array.count > 0 {
                self.tableview.reloadData()
            }

        }


问:
Get specific parts of a file path in Python
I have a path string like

```<code>'/path/eds/vs/accescontrol.dat/d=12520/file1.dat'
</code>```

Q1: How can I get only accescontrol.dat from the path.

Q2: How can I get only /path/eds/vs/accescontrol.dat from the path.

答:
Why not this way

```<code>from pathlib import Path
h=r'C:\Users\dj\Pictures\Saved Pictures'
path = Path(h)
print(path.parts)
</code>```

```<code>Path: .
('C:\\', 'Users', 'dj', 'Pictures', 'Saved Pictures')
</code>```

Body:
I have a path string like

'/path/eds/vs/accescontrol.dat/d=12520/file1.dat'

Q1: How can I get only accescontrol.dat from the path.

Q2: How can I get only /path/eds/vs/accescontrol.dat from the path.

Body:
Why not this way

from pathlib import Path
h=r'C:\Users\dj\Pictures\Saved Pictures'
path = Path(h)
print(path.parts)

Path: .
('C:\\', 'Users', 'dj', 'Pictures', 'Saved Pictures')


问:
NServiceBus property not injecting
I'm running NServiceBus 2.0 and trying to create a service to receive forwarded messages and drop them in a (RavenDB) database. I admit I don't have a firm grasp on how NServiceBus works with IoC containers (nor have I used Spring before), so I may be doing something wrong.

In my IWantToRunOnStartup class, I'm getting a null reference exception where I call Store.Initialize(). Am I hooking up this singleton correctly? Is there anything I need to do in the config files?

Here is the code:

```<code>public class EndpointConfig : IConfigureThisEndpoint, AsA_Server, IWantCustomInitialization
{
    private IMessageRepository _store;

    public void Init()
    {
        _store = new RavenMessageRepository();

        Configure.With()
            .DefaultBuilder()
            .XmlSerializer()
            .UnicastBus();

        Configure.Instance.Configurer.RegisterSingleton<IMessageRepository>(_store);
    }

}

public class StartupConfig : IWantToRunAtStartup
{
    public IMessageRepository Store;

    public void Run()
    {
        Store.Initialize();
    }

    public void Stop()
    {
    }
}
</code>```

Thanks-

答: You need to change your Store member to a property with a get/set. I have not confirmed this, but the container is probably looking for a setter and can't find it(copied from comment so others see it as answered)</p>

Title: NServiceBus property not injecting

Body:
I'm running NServiceBus 2.0 and trying to create a service to receive forwarded messages and drop them in a (RavenDB) database. I admit I don't have a firm grasp on how NServiceBus works with IoC containers (nor have I used Spring before), so I may be doing something wrong.

In my IWantToRunOnStartup class, I'm getting a null reference exception where I call Store.Initialize(). Am I hooking up this singleton correctly? Is there anything I need to do in the config files?

Here is the code:

public class EndpointConfig : IConfigureThisEndpoint, AsA_Server, IWantCustomInitialization
{
    private IMessageRepository _store;

    public void Init()
    {
        _store = new RavenMessageRepository();

        Configure.With()
            .DefaultBuilder()
            .XmlSerializer()
            .UnicastBus();

        Configure.Instance.Configurer.RegisterSingleton<IMessageRepository>(_store);
    }

}

public class StartupConfig : IWantToRunAtStartup
{
    public IMessageRepository Store;

    public void Run()
    {
        Store.Initialize();
    }

    public void Stop()
    {
    }
}

Thanks-


问:
Add extra row to dataframe based on values of other rows
I have a dataframe with two rows of data. I would like to add a third row with values representing the difference between the previous two.

The data is in the following format:

```<code>Month   A   B   C   D   E   F
Jan     1   2   4   8   4   1
Feb     1   1   4   5   2   0
</code>```

I would like to add an extra row with a calculation to give the change across the two months:

```<code>Month   A   B   C   D   E   F
Jan     1   2   4   8   4   1
Feb     1   1   4   5   2   0
Change  0   1   0   3   2   1
</code>```

I've been looking at various functions to add additional rows including rbind and mutate but I'm struggling to perform the calculation in the newly created row.

答:
As it's just two rows you can subtract the individual rows and rbind the difference

```<code>rbind(df, data.frame(Month = "Change", df[1, -1] - df[2, -1]))

#   Month A B C D E F
#1    Jan 1 2 4 8 4 1
#2    Feb 1 1 4 5 2 0
#3 Change 0 1 0 3 2 1
</code>```

Body:
I have a dataframe with two rows of data. I would like to add a third row with values representing the difference between the previous two.

The data is in the following format:

Month   A   B   C   D   E   F
Jan     1   2   4   8   4   1
Feb     1   1   4   5   2   0

I would like to add an extra row with a calculation to give the change across the two months:

Month   A   B   C   D   E   F
Jan     1   2   4   8   4   1
Feb     1   1   4   5   2   0
Change  0   1   0   3   2   1

I've been looking at various functions to add additional rows including rbind and mutate but I'm struggling to perform the calculation in the newly created row.

Body:
As it's just two rows you can subtract the individual rows and rbind the difference

rbind(df, data.frame(Month = "Change", df[1, -1] - df[2, -1]))

#   Month A B C D E F
#1    Jan 1 2 4 8 4 1
#2    Feb 1 1 4 5 2 0
#3 Change 0 1 0 3 2 1


问:
How can I get only one row if only one column is different
I have a table with patient ID's, contact dates and actioncodes. I want to retrieve all rows with actioncodes equal to EPS or D, however i want to keep only one row if the actioncode exists on the same contactdate.

For example this is part of my table, journal:

```<code>PatientID  Contactdate  Actioncode
1          2010-5-6     EPS
1          2010-5-6     D
1          2012-3-4     CNT
1          2013-7-8     D
2          2010-1-4     EPS
2          2010-5-6     D
</code>```

This is the code i have now to retrieve all rows where actioncode is either EPS or D

```<code>select * from journal j where j.actioncode in ('EPS', 'D')
</code>```

I tried group by contactdate, but then i miss the rows where the patients are different. The same effect occurs with distinct(contactdate). What can i use here to return only one row when the date and the patientid are similar and the actioncode is either D or EPS?

Preferred outcome:

```<code>PatientID   Contactd   Actioncode
1           2010-5-6   D
1           2012-3-4   D
2           2010-1-4   EPS
2           2010-5-6   D
</code>```

答:
What you want is a GROUP BY two columns: PatientID and Contactdate. You can use MAX() or MIN() to select one of the rows.

```<code>select
j.PatientID,
j.Contactdate,
MIN(j.actionCode)
from
journal j
where j.actioncode in ('EPS', 'D')
group by j.PatientID, j.Contactdate
</code>```

For match your preferred outcome, you should use MIN().

Body:
I have a table with patient ID's, contact dates and actioncodes. I want to retrieve all rows with actioncodes equal to EPS or D, however i want to keep only one row if the actioncode exists on the same contactdate.

For example this is part of my table, journal:

PatientID  Contactdate  Actioncode
1          2010-5-6     EPS
1          2010-5-6     D
1          2012-3-4     CNT
1          2013-7-8     D
2          2010-1-4     EPS
2          2010-5-6     D

This is the code i have now to retrieve all rows where actioncode is either EPS or D

select * from journal j where j.actioncode in ('EPS', 'D')

I tried group by contactdate, but then i miss the rows where the patients are different. The same effect occurs with distinct(contactdate). What can i use here to return only one row when the date and the patientid are similar and the actioncode is either D or EPS?

Preferred outcome:

PatientID   Contactd   Actioncode
1           2010-5-6   D
1           2012-3-4   D
2           2010-1-4   EPS
2           2010-5-6   D

Body:
What you want is a GROUP BY two columns: PatientID and Contactdate. You can use MAX() or MIN() to select one of the rows.

select
j.PatientID,
j.Contactdate,
MIN(j.actionCode)
from
journal j
where j.actioncode in ('EPS', 'D')
group by j.PatientID, j.Contactdate

For match your preferred outcome, you should use MIN().