问:
How to use QWebEnginePage::OpenLinkInNewTab [Qt5.8]
When I click on link to any question in my feed on Quora using this code, the link doesn't open but it doesn't print "Hello". Could you please tell me where am I wrong? I'm pretty sure that link on quora emits the OpenLinkInNewTab signal. Please help, thanks.

```<code>class WebView : public QObject {
    void newTabRequested() {
        std::cout<<"Hello"<<std::endl;
    }

public:
    char* home_page;
    QAction* newTabAction=new QAction();
    QWebEngineView* view=new QWebEngineView();

    WebView(char* page=(char*)"https://google.com") {
        this->home_page=page;
        this->exitFullScreen->setShortcut(Qt::Key_Escape);

        createWebView();

        this->view->settings()
            ->setAttribute(QWebEngineSettings::JavascriptCanOpenWindows,true);

        this->newTabAction=this->view->pageAction(QWebEnginePage::OpenLinkInNewTab);

        connect(this->newTabAction,&QAction::toggled,this,&WebView::newTabRequested);
    }

    void createWebView() {
        this->view->load(QUrl(this->home_page));
    }
};
</code>```

答:
I think the problem is that newTabRequested is not a slot. Try

```<code>class WebView : public QObject{
    Q_OBJECT

private slots:
    void newTabRequested(){
        std::cout<<"Hello"<<std::endl;
    }

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

Body:
When I click on link to any question in my feed on Quora using this code, the link doesn't open but it doesn't print "Hello". Could you please tell me where am I wrong? I'm pretty sure that link on quora emits the OpenLinkInNewTab signal. Please help, thanks.

class WebView : public QObject {
    void newTabRequested() {
        std::cout<<"Hello"<<std::endl;
    }

public:
    char* home_page;
    QAction* newTabAction=new QAction();
    QWebEngineView* view=new QWebEngineView();

    WebView(char* page=(char*)"https://google.com") {
        this->home_page=page;
        this->exitFullScreen->setShortcut(Qt::Key_Escape);

        createWebView();

        this->view->settings()
            ->setAttribute(QWebEngineSettings::JavascriptCanOpenWindows,true);

        this->newTabAction=this->view->pageAction(QWebEnginePage::OpenLinkInNewTab);

        connect(this->newTabAction,&QAction::toggled,this,&WebView::newTabRequested);
    }

    void createWebView() {
        this->view->load(QUrl(this->home_page));
    }
};

Body:
I think the problem is that newTabRequested is not a slot. Try

class WebView : public QObject{
    Q_OBJECT

private slots:
    void newTabRequested(){
        std::cout<<"Hello"<<std::endl;
    }

    // ...
}


来源: stackexchange

问:
Swift 3 How can I convert this function to return content of json variable
I have this function working fine (feel free if you have a fine tuning !) :

```<code>    func httpPostRequest(urlString: String, dataToPost: Dictionary<String, String>) {

    let url = URL(string: urlString)!
    let session = URLSession.shared
    var request = URLRequest(url: url)

    request.httpMethod = "POST"

    do {
        request.httpBody = try JSONSerialization.data(withJSONObject: dataToPost, options: .prettyPrinted)

    } catch let error {
        print(error.localizedDescription)
    }

    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
        guard error == nil else {
            print("error=\(error) AND error = nil !")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // Check for http(s) errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")
            return
        }

        guard let data = data, error == nil else {                                                 // Check for fundamental networking error
            print("error=\(error)")
            return
        }

        do {
            if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
                print("JSON = ")
                print(json)
           }
        } catch let error {
            print(error.localizedDescription)
            return
        }
    })
    task.resume()
}
</code>```

The PHP server return this JSon string :

```<code>{'exception': false, 'success': false, 'status': -8, 'message': 'Your email address is not valid !', 'confirmMessage': 'null', 'html': 'null', 'data': 'null'}
</code>```

This is what is diplay in the XCode Console :

```<code>JSON =
["status": -8, "data": null, "html": null, "message": Your email address is not valid !, "exception": 0, "confirmMessage": null, "success": 0]
</code>```

I need to return this JSon string to continue with this data.

How can I convert my function for do this ?

答:
This should be the function.</p>

```<code>func httpPostRequest(urlString: String, dataToPost: Dictionary<String, String>, completionHandler:@escaping (Dictionary<String, Any>) -> ()) {

    let url = URL(string: urlString)!
    let session = URLSession.shared
    var request = URLRequest(url: url)

    request.httpMethod = "POST"

    do {
        request.httpBody = try JSONSerialization.data(withJSONObject: dataToPost, options: .prettyPrinted)

    } catch let error {
        print(error.localizedDescription)
    }

    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
        guard error == nil else {
            print("error=\(error) AND error = nil !")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // Check for http(s) errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")
            return
        }

        guard let data = data, error == nil else {                                                 // Check for fundamental networking error
            print("error=\(error)")
            return
        }

        do {
            if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
                print("JSON = ")
                print(json)
                completionHandler(json)
            }
        } catch let error {
            print(error.localizedDescription)
            return
        }
    })
    task.resume()
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have this function working fine (feel free if you have a fine tuning !) :

    func httpPostRequest(urlString: String, dataToPost: Dictionary<String, String>) {

    let url = URL(string: urlString)!
    let session = URLSession.shared
    var request = URLRequest(url: url)

    request.httpMethod = "POST"

    do {
        request.httpBody = try JSONSerialization.data(withJSONObject: dataToPost, options: .prettyPrinted)

    } catch let error {
        print(error.localizedDescription)
    }

    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
        guard error == nil else {
            print("error=\(error) AND error = nil !")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // Check for http(s) errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")
            return
        }

        guard let data = data, error == nil else {                                                 // Check for fundamental networking error
            print("error=\(error)")
            return
        }

        do {
            if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
                print("JSON = ")
                print(json)
           }
        } catch let error {
            print(error.localizedDescription)
            return
        }
    })
    task.resume()
}

The PHP server return this JSon string :

{'exception': false, 'success': false, 'status': -8, 'message': 'Your email address is not valid !', 'confirmMessage': 'null', 'html': 'null', 'data': 'null'}

This is what is diplay in the XCode Console :

JSON =
["status": -8, "data": null, "html": null, "message": Your email address is not valid !, "exception": 0, "confirmMessage": null, "success": 0]

I need to return this JSon string to continue with this data.

How can I convert my function for do this ?

Body:
This should be the function.

func httpPostRequest(urlString: String, dataToPost: Dictionary<String, String>, completionHandler:@escaping (Dictionary<String, Any>) -> ()) {

    let url = URL(string: urlString)!
    let session = URLSession.shared
    var request = URLRequest(url: url)

    request.httpMethod = "POST"

    do {
        request.httpBody = try JSONSerialization.data(withJSONObject: dataToPost, options: .prettyPrinted)

    } catch let error {
        print(error.localizedDescription)
    }

    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
        guard error == nil else {
            print("error=\(error) AND error = nil !")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // Check for http(s) errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")
            return
        }

        guard let data = data, error == nil else {                                                 // Check for fundamental networking error
            print("error=\(error)")
            return
        }

        do {
            if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
                print("JSON = ")
                print(json)
                completionHandler(json)
            }
        } catch let error {
            print(error.localizedDescription)
            return
        }
    })
    task.resume()
}


问:
Remove callback not working in Handler
I have Handler.I call my function every 10 second.Code working perfect,but i can't stop handler.This is my source code

```<code>handler=new Handler();
handler.post(runnable);
public Runnable runnable = new Runnable() {

    @Override
    public void run() {
        myFunction(position);
        handler.postDelayed(runnable,10000);
    }
};
public void myFunction(int position)
{
    if(position>10)
        handler.removeCallbacks(runnable);
}
</code>```

I can call myfunction every 10 second,but i can't stop handler.Ho i can solve my problem?

答:
You remove callback in myFunction but you postDelayed again when myFunction returns, just invert lines inside run()</p>

```<code>@Override
    public void run() {
        handler.postDelayed(runnable,10000);
        myFunction(position);
    }
</code>```

Title: Remove callback not working in Handler

Body:
I have Handler.I call my function every 10 second.Code working perfect,but i can't stop handler.This is my source code

handler=new Handler();
handler.post(runnable);
public Runnable runnable = new Runnable() {

    @Override
    public void run() {
        myFunction(position);
        handler.postDelayed(runnable,10000);
    }
};
public void myFunction(int position)
{
    if(position>10)
        handler.removeCallbacks(runnable);
}

I can call myfunction every 10 second,but i can't stop handler.Ho i can solve my problem?

Body:
You remove callback in myFunction but you postDelayed again when myFunction returns, just invert lines inside run()

@Override
    public void run() {
        handler.postDelayed(runnable,10000);
        myFunction(position);
    }


问:
Remove sql table after x days
I am looking for a way for my system made in C ++ to remove old sqls tables after 90 days, I searched but did not find anything related.

The names of my tables are generated according to the days, for example 20170323

Now the way to remove I can not think of anything that can be done

答: you can have a SQL job that does that. Assuming that tables are generated everyday, you can have a job that read table names from sysobjects table. loop through them and convert table name to datetime, then subtract 90 from current date and compare it with datetime you got from table name.</p>

Title: Remove sql table after x days


问:
Java - is there a way to open a text file if it does not exist already, and append to it if it does exist?
I am pretty new to Java and I came across this problem. I want the java code to make a txt file if it does not exist already, but if it does, I want PrintWriter to append to it using FileWriter. Here is my code:

Edit: I attempted to fix my code but now I am getting the IOException error. What am I doing wrong here?
Edit 2: I think my code is unique since I am trying to make it create a new file if the file does not exist, and make it append to the existing file if it already exists.

```<code>import java.util.Scanner;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;

/**
 * Created by FakeOwl96 on 3/28/2017.
 */
public class AreaOfCircle {
    private static double PI = Math.PI;
    private double radius;
    private static double area;
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        AreaOfCircle a = new AreaOfCircle();
        System.out.print("Type in the radius of circle: ");
        a.radius = keyboard.nextDouble();
        getArea(a.radius);
        System.out.print("Name of the txt file you want to create:");
        String fileName = keyboard.nextLine();
        keyboard.nextLine();
        try {
            File myFile = new File(fileName);
            if (!myFile.exists()) {
                myFile.createNewFile();
            }
            FileWriter fw = new FileWriter(myFile, true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write("The area of the circle is " + area + ".\n");
            bw.close();
        }
        catch (IOException e) {
            System.out.println("IOException Occured");
            e.printStackTrace();
        }
    }

    public static void getArea(double n) {
        area = n * PI;
    }
}
</code>```

答:
Add following line after initializing myFile:

```<code>myFile.createNewFile(); // if file already exists will do nothing
</code>```

Body:
I am pretty new to Java and I came across this problem. I want the java code to make a txt file if it does not exist already, but if it does, I want PrintWriter to append to it using FileWriter. Here is my code:

Edit: I attempted to fix my code but now I am getting the IOException error. What am I doing wrong here?
Edit 2: I think my code is unique since I am trying to make it create a new file if the file does not exist, and make it append to the existing file if it already exists.

import java.util.Scanner;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;

/**
 * Created by FakeOwl96 on 3/28/2017.
 */
public class AreaOfCircle {
    private static double PI = Math.PI;
    private double radius;
    private static double area;
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        AreaOfCircle a = new AreaOfCircle();
        System.out.print("Type in the radius of circle: ");
        a.radius = keyboard.nextDouble();
        getArea(a.radius);
        System.out.print("Name of the txt file you want to create:");
        String fileName = keyboard.nextLine();
        keyboard.nextLine();
        try {
            File myFile = new File(fileName);
            if (!myFile.exists()) {
                myFile.createNewFile();
            }
            FileWriter fw = new FileWriter(myFile, true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write("The area of the circle is " + area + ".\n");
            bw.close();
        }
        catch (IOException e) {
            System.out.println("IOException Occured");
            e.printStackTrace();
        }
    }

    public static void getArea(double n) {
        area = n * PI;
    }
}

Body:
Add following line after initializing myFile:

myFile.createNewFile(); // if file already exists will do nothing


问:
Opening Files for Edit
I am having some trouble with a basic file opening. I can't successfully initiate the filestream. It keeps coming back NULL... Can anyone tell me what I'm missing? I created a "test.dat" file in the same directory that the source code lives.</p>

```<code>#include <stdio.h>
#include <stdlib.h>

int main (void)
{
    if((cfPtr = fopen("test.dat", "rb+")) == NULL) {
        printf("File could not be opened.\n");
    }
    return 0;
}
</code>```

答: When you try to open a file, your OS will look in whatever the process current directory is. This may or may not be the same directory as where your source file lives, depending on your OS and/or IDE.

Title: Opening Files for Edit

Body:
I am having some trouble with a basic file opening. I can't successfully initiate the filestream. It keeps coming back NULL... Can anyone tell me what I'm missing? I created a "test.dat" file in the same directory that the source code lives.

#include <stdio.h>
#include <stdlib.h>

int main (void)
{
    if((cfPtr = fopen("test.dat", "rb+")) == NULL) {
        printf("File could not be opened.\n");
    }
    return 0;
}

ContentLicense: CC BY-SA 2.5


问:
Disabling norms for all fields in elasticsearch
The elasticsearch norms page indicates norms can be disabled on a field-by-field basis dynamically. https://www.elastic.co/guide/en/elasticsearch/reference/current/norms.html

Is there a way to easily do this for all field at once dynamically?

答: Currently, there is no way of doing these changes at once for many fields. The only thing I could propose is to write some script or use Java API, which will disable norms for all needed fields.


问:
Find matching entries in list which are different
I have two lists. The first one contains entries like

RB Leipzig vs SV Darmstadt 98

Hertha Berlin vs Hoffenheim

..

and in the second contains basically the same entries but could but written in different forms. For example:

Hertha BSC vs TSG Hoffenheim

RB Leipzig vs Darmstadt 98

..

and so on. Both lists represent the same sport games but they can use alternate team names and don't appear in the same order.

My goal (hehe pun) is to unify both lists to one and match the same entries and discard entries which don't appear in both lists.

I already tried to use Levensthein distance and fuzzy search.
I thought about using machine learning but have no idea how to start with that.

Would appriciate any help and ideas!

答:
You can solve this problem using Linear Programming combined with the Levenshtein Distance you already mentioned. Linear Programming is a commonly used optimization technique for solving optimization problems, like this one. Check this link to find out an example how to use Solver Foundation in C#. This example isn't related with the specific problem you have, but is a good example how the library works.

Hints:
You need to build a matrix of distances between each pair of teams/strings between 2 lists. Let's say both lists have N elements. In i-th row of the matrix you will have N values, the j-th value will indicate the Levenshtein Distance between i-th element from the first and j-th element from the second list. Then, you need to set the constraints. The constraints would be:

The sum in each row needs to equal 1

The sum in each column equals 1

Each of the coefficient (matrix entry) needs to be either 0 or 1

I have solved the same problem a couple of months ago and this approach worked perfectly for me.

And the cost function would be the sum: `

sum(coef[i][j] * dist[i][j] for i in [1, n] and for j in [1, n])

`. You want to minimize this function, because you want the overall "distance" between the 2 sets after the mapping to be as low as possible.


问:
In Visio, how do I get the normal looking arrows? (The line arrows not the triangle ones)
http://www.dofactory.com/Patterns/PatternFlyweight.aspx

There is a UML diagram on that page. It has three different kinds of connections. The shared aggregation connection, the generalized connection (triangle arrow), and the other one... How do I get the other one in Visio? I can't find it...

Thanks.

答: I think you want the Dynamic Connector which, in the past, would appear as standard among the Basic Flowchart Shapes.


问:
Insert dynamically in the placeholders after writing in the text box
I want to insert data onto placeholders after I write in a text box. I found an alternative solution with Drop-down select:

```<code> <html>
<head>
<script>
function showUser(str) {
    if (str == "") {
        document.getElementById("txtHint").innerHTML = "";
        return;
    } else {
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("txtHint").innerHTML = this.responseText;
            }
        };
        xmlhttp.open("GET","getuser.php?q="+str,true);
        xmlhttp.send();
    }
}
</script>
</head>
<body>

<form>
<select name="users" onchange="showUser(this.value)">
  <option value="">Select a person:</option>
  <option value="1">Peter Griffin</option>
  <option value="2">Lois Griffin</option>
  <option value="3">Joseph Swanson</option>
  <option value="4">Glenn Quagmire</option>
  </select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here...</b></div>

</body>
</html>
</code>```

Php file:

```<code><!DOCTYPE html>
<html>
<head>
<style>
table {
    width: 100%;
    border-collapse: collapse;
}

table, td, th {
    border: 1px solid black;
    padding: 5px;
}

th {text-align: left;}
</style>
</head>
<body>

<?php
$q = intval($_GET['q']);

$con = mysqli_connect('localhost','peter','abc123','my_db');
if (!$con) {
    die('Could not connect: ' . mysqli_error($con));
}

mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM user WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);

echo "<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
    echo "<tr>";
    echo "<td>" . $row['FirstName'] . "</td>";
    echo "<td>" . $row['LastName'] . "</td>";
    echo "<td>" . $row['Age'] . "</td>";
    echo "<td>" . $row['Hometown'] . "</td>";
    echo "<td>" . $row['Job'] . "</td>";
    echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
</html>
</code>```

How to modify it if I want to use with Form::text('foo') and start to start search from mysql table immidiately?

答:
You can replace the <select> with a text input and remove intval() and replaced with a prepared statement, since you don't want to be victim to an SQL injection.

Rererences:

https://en.wikipedia.org/wiki/Prepared_statement

https://en.wikipedia.org/wiki/SQL_injection

You can also use a case insensitive search method/function, and there are a few ways to go about this.

Using MySQL's LIKE function:

https://dev.mysql.com/doc/refman/5.7/en/string-comparison-functions.html

Or a pattern match:

https://dev.mysql.com/doc/refman/5.7/en/pattern-matching.html

Or a WHERE clause:

https://dev.mysql.com/doc/refman/5.7/en/where-optimization.html

Depending on the search criteria.

Body:
I want to insert data onto placeholders after I write in a text box. I found an alternative solution with Drop-down select:

<form>
<select name="users" onchange="showUser(this.value)">
  <option value="">Select a person:</option>
  <option value="1">Peter Griffin</option>
  <option value="2">Lois Griffin</option>
  <option value="3">Joseph Swanson</option>
  <option value="4">Glenn Quagmire</option>
  </select>
</form>

Person info will be listed here...

Php file:

<!DOCTYPE html>

<?php
$q = intval($_GET['q']);

$con = mysqli_connect('localhost','peter','abc123','my_db');
if (!$con) {
    die('Could not connect: ' . mysqli_error($con));
}

mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM user WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);

echo "

Firstname
Lastname
Age
Hometown
Job

";
while($row = mysqli_fetch_array($result)) {
    echo "
";
    echo "" . $row['FirstName'] . "	";
    echo "" . $row['LastName'] . "	";
    echo "" . $row['Age'] . "	";
    echo "" . $row['Hometown'] . "	";
    echo "" . $row['Job'] . "	";
    echo "
";
}
echo "
";
mysqli_close($con);
?>

How to modify it if I want to use with Form::text('foo') and start to start search from mysql table immidiately?


问:
Is there a built-in (no for loop) way to put ranges of a vector into a cell array using a matrix for the indices?
Given:

```<code>data = 0:10;
indices = [1 2; 3 7; 2 5];
</code>```

Is there a one-line way to do this?:

```<code>for i = 1:length(indices)
    out{i} = data(indices(i,1):indices(i,2))
end
</code>```

答:
The following is on</p>

```<code>out = arrayfun(@(ii)data(indices(ii,1):indices(ii,2)),1:size(indices,1),'UniformOutput',false)
</code>```

Body:
Given:

data = 0:10;
indices = [1 2; 3 7; 2 5];

Is there a one-line way to do this?:

for i = 1:length(indices)
    out{i} = data(indices(i,1):indices(i,2))
end

Body:
The following is on

out = arrayfun(@(ii)data(indices(ii,1):indices(ii,2)),1:size(indices,1),'UniformOutput',false)


问:
Jbehave scenario with metafilter and table of parameters
I'm facing an issue with Jbehave, and I don't know what am I doing wrong

I have some scenarios with tables of parameters, and I have to add a meta to these scenarios, when I do that, the test stop running, if I remove the table or remove the meta, everything works fine, but when I put both, the scenario doesn't run

My scenario is the following:

```<code>Scenario: The user do something
Meta: @meta
Given <USER1> exists
When user <USER1> do <ACTION>
Then I verify if <ACTION> has been perfomed

Examples:
|USER1|ACTION|
|userA|actionA|
|userB|actionB|
|userC|actionC|
</code>```

if I let only:

```<code>Scenario: The user do something
Meta: @meta
Given <USER1> exists
When user <USER1> do <ACTION>
Then I verify if <ACTION> has been perfomed
</code>```

or only:

```<code>Scenario: The user do something
Given <USER1> exists
When user <USER1> do <ACTION>
Then I verify if <ACTION> has been perfomed

Examples:
|USER1|ACTION|
|userA|actionA|
|userB|actionB|
|userC|actionC|
</code>```

it works perfectly, but if I add both meta and the examples table, the scenario isn't executed.

Can someone help me?

答:
JBehave Documentation

This page implies that the Meta tag should be BEFORE the scenario.  That is the only thing that stood-out to me.  Why it would only detect it as a problem if the Examples were included hints that it might not be the answer.  Worth a try.

Body:
I'm facing an issue with Jbehave, and I don't know what am I doing wrong

I have some scenarios with tables of parameters, and I have to add a meta to these scenarios, when I do that, the test stop running, if I remove the table or remove the meta, everything works fine, but when I put both, the scenario doesn't run

My scenario is the following:

Scenario: The user do something
Meta: @meta
Given <USER1> exists
When user <USER1> do <ACTION>
Then I verify if <ACTION> has been perfomed

Examples:
|USER1|ACTION|
|userA|actionA|
|userB|actionB|
|userC|actionC|

if I let only:

Scenario: The user do something
Meta: @meta
Given <USER1> exists
When user <USER1> do <ACTION>
Then I verify if <ACTION> has been perfomed

or only:

Scenario: The user do something
Given <USER1> exists
When user <USER1> do <ACTION>
Then I verify if <ACTION> has been perfomed

Examples:
|USER1|ACTION|
|userA|actionA|
|userB|actionB|
|userC|actionC|

it works perfectly, but if I add both meta and the examples table, the scenario isn't executed.

Can someone help me?


问:
Correct nginx configuration to prevent indexing of some folders
I'm using the following Nginx configuration to prevent the indexing of content in some of my folders when I use the x-robots tag

```<code>location ~ .*/(?:archive|filter|topic)/.* {
    add_header X-Robots-Tag "noindex, follow";
}
</code>```

The content remains indexed but I can't debug the Nginx configuration.

My questions: is the configuration I use correct and if I should wait till googlebot re-crawls content and de-indexes the content? Or is my configuration wrong?

答:
The configuration you've written is correct. I'd give one caveat (assuming your config is otherwise standard):

It will only output the X-Robots-Tag when the result code is 200, 201, 204, 206, 301, 302, 303, 304, or 307 (e.g. content matches a disk file, a redirect is issued, etc.). So if you have an /archive/index.html, a hit to http://yoursite.com/archive/ will give the header. If the index.html does not exist (404), you won't see the tag.

The always parameter will output the header for all response codes, assuming the location block is processed:

```<code>location ~ .*/(?:archive|filter|topic)/.* {
    add_header X-Robots-Tag "noindex, follow" always;
}
</code>```

Another option will guarantee the header is output on a URI match. This is useful for when there's a chance that a location block may not get processed (due to short-circuiting, like with return or a last on a rewrite etc):

```<code>http {
    ...
    map $request_uri $robot_header {
        default "";
        ~.*/(?:archive|filter|topic)/.* "noindex, follow";
    }

    server {
        ...
        add_header X-Robots-Tag $robot_header;
        ...
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm using the following Nginx configuration to prevent the indexing of content in some of my folders when I use the x-robots tag

location ~ .*/(?:archive|filter|topic)/.* {
    add_header X-Robots-Tag "noindex, follow";
}

The content remains indexed but I can't debug the Nginx configuration.

My questions: is the configuration I use correct and if I should wait till googlebot re-crawls content and de-indexes the content? Or is my configuration wrong?

Body:
The configuration you've written is correct. I'd give one caveat (assuming your config is otherwise standard):

It will only output the X-Robots-Tag when the result code is 200, 201, 204, 206, 301, 302, 303, 304, or 307 (e.g. content matches a disk file, a redirect is issued, etc.). So if you have an /archive/index.html, a hit to http://yoursite.com/archive/ will give the header. If the index.html does not exist (404), you won't see the tag.

The always parameter will output the header for all response codes, assuming the location block is processed:

location ~ .*/(?:archive|filter|topic)/.* {
    add_header X-Robots-Tag "noindex, follow" always;
}

Another option will guarantee the header is output on a URI match. This is useful for when there's a chance that a location block may not get processed (due to short-circuiting, like with return or a last on a rewrite etc):

http {
    ...
    map $request_uri $robot_header {
        default "";
        ~.*/(?:archive|filter|topic)/.* "noindex, follow";
    }

    server {
        ...
        add_header X-Robots-Tag $robot_header;
        ...
    }


答: Are you using Visual Studio? You have to put test.dat into the Debug directory. There are two debug directory in newer version, you have to check that yourself.

Title: Opening Files for Edit


问:
User defined Ordering using Stream in Java 8
I am new to the Java 8 Stream API.I have below requirement My ordering rule is : "A","C","D","B"

   I have result which having Object containing 8-9 elements and duplicate elements also.

Below is my code :

```<code>public class A
{
private String name;
    public A()
    {
    }
    public A(String name )
    {
     this.name=name;
    }
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return "A [name=" + name + "]";
    }
</code>```

I have another class :

```<code>public class B
{
   enum TypeEnum{
    A("A"),
    C("C"),
    D("D"),
   B("B");

    private String s;

    private TypeEnum(String s) {
        this.s = s;
    }
}

public static void main(String agrs[] )
   {

   Collection<A> stringCollection = new ArrayList<>();
    stringCollection.add(new A("A"));
    stringCollection.add(new A("D"));
    stringCollection.add(new A("D"));
    stringCollection.add(new A("C"));
    stringCollection.add(new A("D"));
    stringCollection.add(new A("B"));
    stringCollection.add(new A("A"));
    stringCollection.add(new A("A"));

    Predicate<A> aPredicate = a -> a.getName() == TypeEnum.A.name();
    Predicate<A> cPredicate =  a -> a.getName()== TypeEnum.C.name();
    Predicate<A> dPredicate =  a -> a.getName()== TypeEnum.D.name();
    Predicate<A> bPredicate =  a -> a.getName()== TypeEnum.B.name();

    Predicate<A> fullPredicate = aPredicate.and(cPredicate)
            .and(dPredicate).and(bPredicate);

    List<A> list= stringCollection.stream().filter(fullPredicate).collect(Collectors.toList());

    System.out.println(list);
    }
</code>```

Here the output should be A,A,A,C,D,D,D,B

I want to order the element as per the specified rule as per the mention in above using Stream java 8 API. Class A is a object which is used in class B to put the value in the list which is type of Class A. The final result should be ordered as per the defined ordering rule. It would be great and thankful if anybody face the same issue and having solution for the same.

答:
You can simply sort by a given list’s position:

```<code>List<String> order = Arrays.asList("A", "C", "D", "B");
List<A> result = collection.stream()
    .sorted(Comparator.comparingInt(a -> order.indexOf(a.getName())))
    .collect(Collectors.toList());
</code>```

This will put names not specified in the list at the front. You move them to the end instead, by using the comparator Comparator.comparingInt(a -> order.indexOf(a.getName())+Integer.MIN_VALUE).

Due to the repeated use of indexOf, this will not scale well for a larger order list.

An alternative is a bucket sort variant:

```<code>Map<String, List<A>> m = collection.stream().collect(Collectors.groupingBy(A::getName));
List<A> result = Stream.of("A", "C", "D", "B")
    .flatMap(s -> m.getOrDefault(s, Collections.emptyList()).stream())
    .collect(Collectors.toList());
</code>```

Here, names not specified won’t show up in the result at all. It will have a better time complexity, but might consume more memory temporarily.

Body:
I am new to the Java 8 Stream API.I have below requirement My ordering rule is : "A","C","D","B"

   I have result which having Object containing 8-9 elements and duplicate elements also.

Below is my code :

public class A
{
private String name;
    public A()
    {
    }
    public A(String name )
    {
     this.name=name;
    }
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return "A [name=" + name + "]";
    }

I have another class :

public class B
{
   enum TypeEnum{
    A("A"),
    C("C"),
    D("D"),
   B("B");

    private String s;

    private TypeEnum(String s) {
        this.s = s;
    }
}

public static void main(String agrs[] )
   {

   Collection stringCollection = new ArrayList<>();
    stringCollection.add(new A("A"));
    stringCollection.add(new A("D"));
    stringCollection.add(new A("D"));
    stringCollection.add(new A("C"));
    stringCollection.add(new A("D"));
    stringCollection.add(new A("B"));
    stringCollection.add(new A("A"));
    stringCollection.add(new A("A"));

    Predicate aPredicate = a -> a.getName() == TypeEnum.A.name();
    Predicate cPredicate =  a -> a.getName()== TypeEnum.C.name();
    Predicate dPredicate =  a -> a.getName()== TypeEnum.D.name();
    Predicate bPredicate =  a -> a.getName()== TypeEnum.B.name();

    Predicate fullPredicate = aPredicate.and(cPredicate)
            .and(dPredicate).and(bPredicate);

    List list= stringCollection.stream().filter(fullPredicate).collect(Collectors.toList());

    System.out.println(list);
    }

Here the output should be A,A,A,C,D,D,D,B

I want to order the element as per the specified rule as per the mention in above using Stream java 8 API. Class A is a object which is used in class B to put the value in the list which is type of Class A. The final result should be ordered as per the defined ordering rule. It would be great and thankful if anybody face the same issue and having solution for the same.

Body:
You can simply sort by a given list’s position:

List<String> order = Arrays.asList("A", "C", "D", "B");
List<A> result = collection.stream()
    .sorted(Comparator.comparingInt(a -> order.indexOf(a.getName())))
    .collect(Collectors.toList());

This will put names not specified in the list at the front. You move them to the end instead, by using the comparator Comparator.comparingInt(a -> order.indexOf(a.getName())+Integer.MIN_VALUE).

Due to the repeated use of indexOf, this will not scale well for a larger order list.

An alternative is a bucket sort variant:

Map<String, List<A>> m = collection.stream().collect(Collectors.groupingBy(A::getName));
List<A> result = Stream.of("A", "C", "D", "B")
    .flatMap(s -> m.getOrDefault(s, Collections.emptyList()).stream())
    .collect(Collectors.toList());

Here, names not specified won’t show up in the result at all. It will have a better time complexity, but might consume more memory temporarily.


问:
how to set multiple Alarm in android to perform time-based operations outside the lifetime of my application?
In the main activity of my application , there are two text field where the users insert date and time and a button start. When the button start is clicked , it is invokes the method setProgrammedTimer of the broadcastReceiver class that sets an alarm at date and time inserted by users and at these date and time, the application invokes the activity DIAL phone. But if i insert one date and one time and i click start button, and after i insert a new date and time and i click start button, the application run only the second alarm. how can i do to execute both alarms?

This the button start code on main activity:

```<code> start.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            year = Integer.valueOf(yearT.getText().toString());
            month = Integer.valueOf(monthT.getText().toString());
            day = Integer.valueOf(dayT.getText().toString());
            hour = Integer.valueOf(hourT.getText().toString());
            minute = Integer.valueOf(minuteT.getText().toString());
      timer.setProgrammedTimer(context,year,month,day,hour,minute);
</code>```

This is the broadcastReceiver code:

```<code>public class TimerBroadcast extends BroadcastReceiver {

@Override
public void onReceive(final Context context, Intent intent) {

    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
    wl.acquire();
    Intent callIntent = new Intent(Intent.ACTION_DIAL);
    callIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(callIntent);
    wl.release();

}

public void setProgrammedTimer(Context context,int year, int month,int day, int hour, int minute){

    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context,TimerBroadcast.class);
    PendingIntent pi = PendingIntent.getBroadcast(context,0,intent, PendingIntent.FLAG_CANCEL_CURRENT);
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(System.currentTimeMillis());
    cal.set(Calendar.YEAR,anno);
    cal.set(Calendar.MONTH,mese-1);
    cal.set(Calendar.DAY_OF_MONTH,giorno);
    cal.set(Calendar.HOUR_OF_DAY,ora);
    cal.set(Calendar.MINUTE,minuti);
    cal.set(Calendar.SECOND,0);
    am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pi);
}
</code>```

答:
When you are adding second alarm you are cancelling the first.

```<code>PendingIntent pi = PendingIntent.getBroadcast(context,0,intent, PendingIntent.FLAG_CANCEL_CURRENT);
</code>```

Note FLAG_CANCEL_CURRENT.

Body:
In the main activity of my application , there are two text field where the users insert date and time and a button start. When the button start is clicked , it is invokes the method setProgrammedTimer of the broadcastReceiver class that sets an alarm at date and time inserted by users and at these date and time, the application invokes the activity DIAL phone. But if i insert one date and one time and i click start button, and after i insert a new date and time and i click start button, the application run only the second alarm. how can i do to execute both alarms?

This the button start code on main activity:

 start.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            year = Integer.valueOf(yearT.getText().toString());
            month = Integer.valueOf(monthT.getText().toString());
            day = Integer.valueOf(dayT.getText().toString());
            hour = Integer.valueOf(hourT.getText().toString());
            minute = Integer.valueOf(minuteT.getText().toString());
      timer.setProgrammedTimer(context,year,month,day,hour,minute);

This is the broadcastReceiver code:

public class TimerBroadcast extends BroadcastReceiver {

@Override
public void onReceive(final Context context, Intent intent) {

    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
    wl.acquire();
    Intent callIntent = new Intent(Intent.ACTION_DIAL);
    callIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(callIntent);
    wl.release();

}

public void setProgrammedTimer(Context context,int year, int month,int day, int hour, int minute){

    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context,TimerBroadcast.class);
    PendingIntent pi = PendingIntent.getBroadcast(context,0,intent, PendingIntent.FLAG_CANCEL_CURRENT);
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(System.currentTimeMillis());
    cal.set(Calendar.YEAR,anno);
    cal.set(Calendar.MONTH,mese-1);
    cal.set(Calendar.DAY_OF_MONTH,giorno);
    cal.set(Calendar.HOUR_OF_DAY,ora);
    cal.set(Calendar.MINUTE,minuti);
    cal.set(Calendar.SECOND,0);
    am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pi);
}

Body:
When you are adding second alarm you are cancelling the first.

PendingIntent pi = PendingIntent.getBroadcast(context,0,intent, PendingIntent.FLAG_CANCEL_CURRENT);

Note FLAG_CANCEL_CURRENT.


问:
Fine tuning Django queryset retrieval
In a Django app of mine, I need to display, for a list of users (called user_ids), their:

username, avatar and score.

The username is retrieved from the User model, whereas avatar and score are present in the UserProfile model (that has a one-to-one field point to the User model, called user).

Currently my approach is to fetch the full objects (see below), even though I just need 3 attributes from the two models.

What's the most efficient way for me to just retrieve just the required fields, nothing else? Now I know i can do:

```<code>usernames = User.objects.filter(id__in=user_ids).values_list('username',flat=True)
scores_and_avatars = UserProfile.objects.filter(user_id__in=user_ids).values_list('score','avatar')
</code>```

However, these give me separate querysets, so I can't iterate over them as a unified object_list and show each user's username, score and avatar in a Django template. So what would be the most efficient, light-weight way to retrieve and put this information together?

Currently, I'm doing the following to retrieve these three fields: queryset = User.objects.select_related('userprofile').filter(id__in=user_ids)

答:
The most efficient way it's use values, your query will look like this:

```<code>usernames = User.objects.filter(id__in=user_ids).values('username', 'userprofile__score', 'userprofile__avatar')
</code>```

This solution will return dictionary, but you can try to use only instead of values, it'll create django model object with specified fields, but if you will try to access not specified field it'll generate additional query.

```<code>usernames = User.objects.filter(id__in=user_ids).select_related('userprofile').only('username', 'userprofile__score', 'userprofile__avatar')
</code>```

Title: Fine tuning Django queryset retrieval

Body:
In a Django app of mine, I need to display, for a list of users (called user_ids), their:

username, avatar and score.

The username is retrieved from the User model, whereas avatar and score are present in the UserProfile model (that has a one-to-one field point to the User model, called user).

Currently my approach is to fetch the full objects (see below), even though I just need 3 attributes from the two models.

What's the most efficient way for me to just retrieve just the required fields, nothing else? Now I know i can do:

usernames = User.objects.filter(id__in=user_ids).values_list('username',flat=True)
scores_and_avatars = UserProfile.objects.filter(user_id__in=user_ids).values_list('score','avatar')

However, these give me separate querysets, so I can't iterate over them as a unified object_list and show each user's username, score and avatar in a Django template. So what would be the most efficient, light-weight way to retrieve and put this information together?

Currently, I'm doing the following to retrieve these three fields: queryset = User.objects.select_related('userprofile').filter(id__in=user_ids)

Body:
The most efficient way it's use values, your query will look like this:

usernames = User.objects.filter(id__in=user_ids).values('username', 'userprofile__score', 'userprofile__avatar')

This solution will return dictionary, but you can try to use only instead of values, it'll create django model object with specified fields, but if you will try to access not specified field it'll generate additional query.

usernames = User.objects.filter(id__in=user_ids).select_related('userprofile').only('username', 'userprofile__score', 'userprofile__avatar')


答:
This is an example of file append line and create new file if file is not exists.</p>

```<code>import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class AppendFileDemo {

    public static void main(String[] args) {
        try {
            String content = "This is my content which would be appended "
                    + "at the end of the specified file";
            //Specify the file name and path here
            File file = new File("myfile.txt");

            /* This logic is to create the file if the
         * file is not already present
             */
            if (!file.exists()) {
                file.createNewFile();
            }

            //Here true is to append the content to file
            FileWriter fw = new FileWriter(file, true);
            //BufferedWriter writer give better performance
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(content);
            //Closing BufferedWriter Stream
            bw.close();

            System.out.println("Data successfully appended at the end of file");

        } catch (IOException ioe) {
            System.out.println("Exception occurred:");
            ioe.printStackTrace();
        }
    }
}
</code>```

Title: Java - is there a way to open a text file if it does not exist already, and append to it if it does exist?

Body:
This is an example of file append line and create new file if file is not exists.

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class AppendFileDemo {

    public static void main(String[] args) {
        try {
            String content = "This is my content which would be appended "
                    + "at the end of the specified file";
            //Specify the file name and path here
            File file = new File("myfile.txt");

            /* This logic is to create the file if the
         * file is not already present
             */
            if (!file.exists()) {
                file.createNewFile();
            }

            //Here true is to append the content to file
            FileWriter fw = new FileWriter(file, true);
            //BufferedWriter writer give better performance
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(content);
            //Closing BufferedWriter Stream
            bw.close();

            System.out.println("Data successfully appended at the end of file");

        } catch (IOException ioe) {
            System.out.println("Exception occurred:");
            ioe.printStackTrace();
        }
    }
}


问:
PHP MySQL Group BY Having issue
Suppose I have a table like:

```<code>ID|Word |Reference
1 |Dog  |1
1 |Fish |2
1 |Sheep|3
2 |Dog  |4
2 |Fish |5
3 |Sheep|6
4 |Dog  |7
</code>```

I want to select all ID's that have the word Dog AND Sheep. So the result should be ID's: 1 and 2. I tried using this query:

```<code>SELECT ID FROM `Table` WHERE Word='Dog' OR Word='Fish' GROUP BY ID Having Word='Dog AND Word='Fish'
</code>```

However, this AND in the Having clause makes me get 0 results. So, am I doing something wrong or is there another way to achieve wat I want based on MySQL query only (to optimize speed, since it has to search through many rows with the same setup as in the example above)

Basically the problem is the AND statement over multiple rows with the same ID.

UPDATE:

I need to get the reference for the ID's that where found. E.g. when the ID 1 and 2 are returned I need to know that ID 1 has reference 1 and 2. ID 2 has reference 3 and 4. Currently, I'm using this query:

```<code>SELECT ID FROM `Test` WHERE Word in ('Dog', 'Fish') GROUP BY ID HAVING  count(DISTINCT Word) = 2;
</code>```

Thanks

答:
The answer for my problem is solved using underneath query:

```<code>SELECT ID, GROUP_CONCAT(Reference) as ReferencesGrouped FROM `Test` WHERE Word in ('Dog', 'Fish') GROUP BY ID HAVING  count(DISTINCT Word) = 2;
</code>```

This will return me:

```<code>ID|ReferencesGrouped
1 |1,4
2 |4,5
</code>```

Title: PHP MySQL Group BY Having issue

Body:
Suppose I have a table like:

ID|Word |Reference
1 |Dog  |1
1 |Fish |2
1 |Sheep|3
2 |Dog  |4
2 |Fish |5
3 |Sheep|6
4 |Dog  |7

I want to select all ID's that have the word Dog AND Sheep. So the result should be ID's: 1 and 2. I tried using this query:

SELECT ID FROM `Table` WHERE Word='Dog' OR Word='Fish' GROUP BY ID Having Word='Dog AND Word='Fish'

However, this AND in the Having clause makes me get 0 results. So, am I doing something wrong or is there another way to achieve wat I want based on MySQL query only (to optimize speed, since it has to search through many rows with the same setup as in the example above)

Basically the problem is the AND statement over multiple rows with the same ID.

UPDATE:

I need to get the reference for the ID's that where found. E.g. when the ID 1 and 2 are returned I need to know that ID 1 has reference 1 and 2. ID 2 has reference 3 and 4. Currently, I'm using this query:

SELECT ID FROM `Test` WHERE Word in ('Dog', 'Fish') GROUP BY ID HAVING  count(DISTINCT Word) = 2;

Thanks

Body:
The answer for my problem is solved using underneath query:

SELECT ID, GROUP_CONCAT(Reference) as ReferencesGrouped FROM `Test` WHERE Word in ('Dog', 'Fish') GROUP BY ID HAVING  count(DISTINCT Word) = 2;

This will return me:

ID|ReferencesGrouped
1 |1,4
2 |4,5


问:
Cache locality with unique_ptr
I have a vector of custom classes (std::string just for example).

The vector is large and I iterate through often, so I rely on cache locality.

I also have one raw pointer which points at one of the vector elements.

Now is the trick:

The vector is sorted from time to time, so the raw pointer loose the actual pointed element value, and will point to some random element value.

Here is an example to illustrate the same:

```<code>#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <memory>

using namespace std;

int main()
{

    vector<string> v = {"9","3", "8", "7", "6", "5", "1", "4", "2"};

    string* rs = &v[7]; //point to the 7th element

    for (size_t i = 0; i < v.size(); ++i)
        cerr << v[i];
    cerr << endl;
    cerr << "Referenced string: " << rs->c_str() << endl;

    cerr << "Sort ..." << endl;
    sort(v.begin(), v.end(), [](const string& a, const string& b)
    {
        if (a < b)
            return true;
        else
            return false;
    }
    );

    for (size_t i = 0; i < v.size(); ++i)
        cerr << v[i];
    cerr << endl;
    cerr << "Referenced string: " << rs->c_str() << endl;

    cin.get();
    return 0;

}
</code>```

Output:

```<code>938765142
Referenced string before sort : 4
Sort ...
123456789
Referenced string after sort : 8
</code>```

Since I wish the rs pointer to keep pointing to the 7th element value (which is 4) even after the sort, I came up with the following solution (vector of pointers):

```<code>#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <memory>

using namespace std;

int main()
{

    vector<unique_ptr<string>> v;
    v.resize(9);
    v[0] = make_unique<string>("9");
    v[1] = make_unique<string>("3");
    v[2] = make_unique<string>("8");
    v[3] = make_unique<string>("7");
    v[4] = make_unique<string>("6");
    v[5] = make_unique<string>("5");
    v[6] = make_unique<string>("1");
    v[7] = make_unique<string>("4");
    v[8] = make_unique<string>("2");

    string* rs = v[7].get();

    for (size_t i = 0; i < v.size(); ++i)
    cerr << v[i]->c_str();
    cerr << endl;
    cerr << "Referenced string before sort: " << rs->c_str() << endl;

    cerr << "Sort ..." << endl;
    sort(v.begin(), v.end(), [](const unique_ptr<string>& a, const unique_ptr<string>& b)
    {
    if (*a < *b)
    return true;
    else
    return false;
    }
    );

    for (size_t i = 0; i < v.size(); ++i)
    cerr << v[i]->c_str();
    cerr << endl;
    cerr << "Referenced string after sort: " << rs->c_str() << endl;

    cin.get();
    return 0;

}
</code>```

Output:

```<code>938765142
Referenced string before sort: 4
Sort ...
123456789
Referenced string after sort: 4
</code>```

While this latter solution works, there is a price: I have lost the cache locality of my vector, since I store pointers in it, rather than the actual objects.

Is there a way to maintain cache locality (e.g.: store my actual objects in the vector), and somehow manage to rs pointer to keep track where its pointed value wander around due to the sorts?
Or from the other perspective, is there a way to achieve cache locality with the vector of pointers?

Solution from Pubby, thanks!:

```<code>#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <memory>

using namespace std;

int main()
{

    vector<string> data = { "d","e", "f", "g", "i", "b", "c", "a", "h" };
    vector<int> indexes = {0,1,2,3,4,5,6,7,8};

    int si = 6;

    for (size_t i = 0; i < indexes.size(); ++i)
        cerr << indexes[i];
    cerr << endl;
    for (size_t i = 0; i < indexes.size(); ++i)
        cerr << data[indexes[i]];
    cerr << endl;
    cerr << "Referenced string before sort: " << data[si] << endl;

    cerr << "Sort ..." << endl;
    sort(indexes.begin(), indexes.end(), [&](const int a, const int b)
    {
        return data[a] < data[b];
    }
    );

    for (size_t i = 0; i < indexes.size(); ++i)
        cerr << indexes[i];
    cerr << endl;
    for (size_t i = 0; i < indexes.size(); ++i)
        cerr << data[indexes[i]];
    cerr << endl;
    cerr << "Referenced string after sort: " << data[si] << endl;

    cin.get();
    return 0;

}
</code>```

答:
You can increase locality by storing the strings in a vector which doesn't change, and then store a vector of pointers/indexes to these strings.

Like this:

```<code>vector<string> data = {"9","3", "8", "7", "6", "5", "1", "4", "2"};
vector<unsigned> indexes(data.size());
std::iota(indexes.begin(), indexes.end(), 0u);
</code>```

To sort your data you'd sort indexes using a custom comparator function which retrieves the values from data and compares them. Remember: indexes can change, but data should not!

```<code>sort(indexes.begin(), indexes.end(), [&](unsigned a, unsigned b)
    {
        return data[a] < data[b];
    });
</code>```

Title: Cache locality with unique_ptr

Body:
I have a vector of custom classes (std::string just for example).

The vector is large and I iterate through often, so I rely on cache locality.

I also have one raw pointer which points at one of the vector elements.

Now is the trick:

The vector is sorted from time to time, so the raw pointer loose the actual pointed element value, and will point to some random element value.

Here is an example to illustrate the same:

#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <memory>

using namespace std;

int main()
{

    vector<string> v = {"9","3", "8", "7", "6", "5", "1", "4", "2"};

    string* rs = &v[7]; //point to the 7th element

    for (size_t i = 0; i < v.size(); ++i)
        cerr << v[i];
    cerr << endl;
    cerr << "Referenced string: " << rs->c_str() << endl;

    cerr << "Sort ..." << endl;
    sort(v.begin(), v.end(), [](const string& a, const string& b)
    {
        if (a < b)
            return true;
        else
            return false;
    }
    );

    for (size_t i = 0; i < v.size(); ++i)
        cerr << v[i];
    cerr << endl;
    cerr << "Referenced string: " << rs->c_str() << endl;

    cin.get();
    return 0;

}

Output:

938765142
Referenced string before sort : 4
Sort ...
123456789
Referenced string after sort : 8

Since I wish the rs pointer to keep pointing to the 7th element value (which is 4) even after the sort, I came up with the following solution (vector of pointers):

#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <memory>

using namespace std;

int main()
{

    vector<unique_ptr<string>> v;
    v.resize(9);
    v[0] = make_unique<string>("9");
    v[1] = make_unique<string>("3");
    v[2] = make_unique<string>("8");
    v[3] = make_unique<string>("7");
    v[4] = make_unique<string>("6");
    v[5] = make_unique<string>("5");
    v[6] = make_unique<string>("1");
    v[7] = make_unique<string>("4");
    v[8] = make_unique<string>("2");

    string* rs = v[7].get();

    for (size_t i = 0; i < v.size(); ++i)
    cerr << v[i]->c_str();
    cerr << endl;
    cerr << "Referenced string before sort: " << rs->c_str() << endl;

    cerr << "Sort ..." << endl;
    sort(v.begin(), v.end(), [](const unique_ptr<string>& a, const unique_ptr<string>& b)
    {
    if (*a < *b)
    return true;
    else
    return false;
    }
    );

    for (size_t i = 0; i < v.size(); ++i)
    cerr << v[i]->c_str();
    cerr << endl;
    cerr << "Referenced string after sort: " << rs->c_str() << endl;

    cin.get();
    return 0;

}

Output:

938765142
Referenced string before sort: 4
Sort ...
123456789
Referenced string after sort: 4

While this latter solution works, there is a price: I have lost the cache locality of my vector, since I store pointers in it, rather than the actual objects.

Is there a way to maintain cache locality (e.g.: store my actual objects in the vector), and somehow manage to rs pointer to keep track where its pointed value wander around due to the sorts?
Or from the other perspective, is there a way to achieve cache locality with the vector of pointers?

Solution from Pubby, thanks!:

#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <memory>

using namespace std;

int main()
{

    vector<string> data = { "d","e", "f", "g", "i", "b", "c", "a", "h" };
    vector<int> indexes = {0,1,2,3,4,5,6,7,8};

    int si = 6;

    for (size_t i = 0; i < indexes.size(); ++i)
        cerr << indexes[i];
    cerr << endl;
    for (size_t i = 0; i < indexes.size(); ++i)
        cerr << data[indexes[i]];
    cerr << endl;
    cerr << "Referenced string before sort: " << data[si] << endl;

    cerr << "Sort ..." << endl;
    sort(indexes.begin(), indexes.end(), [&](const int a, const int b)
    {
        return data[a] < data[b];
    }
    );

    for (size_t i = 0; i < indexes.size(); ++i)
        cerr << indexes[i];
    cerr << endl;
    for (size_t i = 0; i < indexes.size(); ++i)
        cerr << data[indexes[i]];
    cerr << endl;
    cerr << "Referenced string after sort: " << data[si] << endl;

    cin.get();
    return 0;

}

Body:
You can increase locality by storing the strings in a vector which doesn't change, and then store a vector of pointers/indexes to these strings.

Like this:

vector<string> data = {"9","3", "8", "7", "6", "5", "1", "4", "2"};
vector<unsigned> indexes(data.size());
std::iota(indexes.begin(), indexes.end(), 0u);

To sort your data you'd sort indexes using a custom comparator function which retrieves the values from data and compares them. Remember: indexes can change, but data should not!

sort(indexes.begin(), indexes.end(), [&](unsigned a, unsigned b)
    {
        return data[a] < data[b];
    });


问:
Math.pow(x,2) area of square
i am running a code, but i dont seem to be able to get the scanner working, anyone got an idea how?

```<code>public class verk34 {

public static void main(String[] args) {

 System.out.println(Math.pow(x,2));
 }
}
</code>```

the thing is inserting a number on your own without altering the code.

答:
First, you need to import scanner and Math

```<code>import java.util.Scanner
import java.lang.Math
</code>```

Then If I am understanding correctly the problem, you need to do this in two steps :

-Instantiate a scanner and collect user input as an integer.

```<code>Scanner sc = new Scanner(System.in);
System.out.println(" Please enter the square area :");

int userValue = sc.nextInt();
</code>```

The nextInt method will lock process and wait for a keyboard event before continuing. So enter a nulber with your keyboard.

-Use System.out.println with given value.

```<code>System.out.println(Math.pow(userValue,2));
</code>```

Title: Math.pow(x,2) area of square

Body:
i am running a code, but i dont seem to be able to get the scanner working, anyone got an idea how?

public class verk34 {

public static void main(String[] args) {

 System.out.println(Math.pow(x,2));
 }
}

the thing is inserting a number on your own without altering the code.

Body:
First, you need to import scanner and Math

import java.util.Scanner
import java.lang.Math

Then If I am understanding correctly the problem, you need to do this in two steps :

-Instantiate a scanner and collect user input as an integer.

Scanner sc = new Scanner(System.in);
System.out.println(" Please enter the square area :");

int userValue = sc.nextInt();

The nextInt method will lock process and wait for a keyboard event before continuing. So enter a nulber with your keyboard.

-Use System.out.println with given value.

System.out.println(Math.pow(userValue,2));


问:
Ruby on Rails NameError: uninitialized constant
I just set up a new migration and model relationships, and in console when testing the relationship between tables I get the following error: NameError: uninitialized constant.

Does anyone have any idea what is wrong?

Thank you

Edit:

Here's the error

```<code>NameError: uninitialized constant Profile::ProfileNotification
  from C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:105:in `const_missing'
  from C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2199:in `compute_type'
  from C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/core_ext/kernel/reporting.rb:11:in `silence_warnings'
  from C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2195:in `compute_type'
  from C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/reflection.rb:156:in `send'
  from C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/reflection.rb:156:in `klass'
  from C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/reflection.rb:187:in `quoted_table_name'
  from C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/associations/has_many_association.rb:97:in `construct_sql'
  from C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/associations/association_collection.rb:21:in `initialize'
  from C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/associations.rb:1300:in `new'
  from C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/associations.rb:1300:in `profile_notifications'
  from (irb):3
</code>```

Code from the ProfileNotification migration:

```<code>class CreateProfileNotifications < ActiveRecord::Migration
  def self.up
    create_table :profile_notifications do |t|
      t.integer :profile_id, :null => false
      t.integer :notification_id, :null => false
      t.string :notification_text
      t.boolean :checked, :default => false
      t.boolean :update_reply, :default => false
      t.boolean :opinion_reply, :default => false
      t.boolean :message_reply, :default => false
      t.boolean :pm, :default => false
      t.boolean :accepted_friend, :default => false
      t.boolean :accepted_supporter, :default => false
      t.timestamps
    end
  end

  def self.down
    drop_table :profile_notifications
  end
end
</code>```

答:
It's breaking because you're referencing Profile::ProfileNotification which doesn't exist.

Rails considers this a model named ProfileNotification located in the Profile namespace, but your comment suggests that Profile is another model class and not a namespace.

Based on the migration you have posted, I think you're confused about the Rails naming convention for one-to-many relationships. Here's how I think it's supposed to look:

```<code>class CreateNotifications < ActiveRecord::Migration
  def self.up
    create_table :notifications do |t|
      t.references :profile
      t.text :body
      t.boolean :checked, :default => false
      t.boolean :update_reply, :default => false
      t.boolean :opinion_reply, :default => false
      t.boolean :message_reply, :default => false
      t.boolean :pm, :default => false
      t.boolean :accepted_friend, :default => false
      t.boolean :accepted_supporter, :default => false
      t.timestamps
    end
  end

  def self.down
    drop_table :notifications
  end
end

class Profile < ActiveRecord::Base
  has_many :notifications
end

class Notification < ActiveRecord::Base
  belongs_to :profile
end
</code>```

Now when you execute Profile.find(1).notifications you should get a list of the associated notifications to that profile.

More information: Active Record Associations

Body:
I just set up a new migration and model relationships, and in console when testing the relationship between tables I get the following error: NameError: uninitialized constant.

Does anyone have any idea what is wrong?

Thank you

Edit:

Here's the error

NameError: uninitialized constant Profile::ProfileNotification
  from C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:105:in `const_missing'
  from C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2199:in `compute_type'
  from C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/core_ext/kernel/reporting.rb:11:in `silence_warnings'
  from C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2195:in `compute_type'
  from C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/reflection.rb:156:in `send'
  from C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/reflection.rb:156:in `klass'
  from C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/reflection.rb:187:in `quoted_table_name'
  from C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/associations/has_many_association.rb:97:in `construct_sql'
  from C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/associations/association_collection.rb:21:in `initialize'
  from C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/associations.rb:1300:in `new'
  from C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/associations.rb:1300:in `profile_notifications'
  from (irb):3

Code from the ProfileNotification migration:

class CreateProfileNotifications < ActiveRecord::Migration
  def self.up
    create_table :profile_notifications do |t|
      t.integer :profile_id, :null => false
      t.integer :notification_id, :null => false
      t.string :notification_text
      t.boolean :checked, :default => false
      t.boolean :update_reply, :default => false
      t.boolean :opinion_reply, :default => false
      t.boolean :message_reply, :default => false
      t.boolean :pm, :default => false
      t.boolean :accepted_friend, :default => false
      t.boolean :accepted_supporter, :default => false
      t.timestamps
    end
  end

  def self.down
    drop_table :profile_notifications
  end
end

Body:
It's breaking because you're referencing Profile::ProfileNotification which doesn't exist.

Rails considers this a model named ProfileNotification located in the Profile namespace, but your comment suggests that Profile is another model class and not a namespace.

Based on the migration you have posted, I think you're confused about the Rails naming convention for one-to-many relationships. Here's how I think it's supposed to look:

class CreateNotifications < ActiveRecord::Migration
  def self.up
    create_table :notifications do |t|
      t.references :profile
      t.text :body
      t.boolean :checked, :default => false
      t.boolean :update_reply, :default => false
      t.boolean :opinion_reply, :default => false
      t.boolean :message_reply, :default => false
      t.boolean :pm, :default => false
      t.boolean :accepted_friend, :default => false
      t.boolean :accepted_supporter, :default => false
      t.timestamps
    end
  end

  def self.down
    drop_table :notifications
  end
end

class Profile < ActiveRecord::Base
  has_many :notifications
end

class Notification < ActiveRecord::Base
  belongs_to :profile
end

Now when you execute Profile.find(1).notifications you should get a list of the associated notifications to that profile.

More information: Active Record Associations


问:
JavaMail - Issue with Multiple And Search Terms
I would like to fetch recent, unread emails with a specific subject in a particular folder from my gmail account. I am using JavaMail API as below but it returns 0 results. However if I just use subjectTerm alone, I see results. Please let me know where am I going wrong. Thank you.

Please note that I used  messages[0] below instead of looping through messages array for code simplicity to paste it here.

```<code>     public void openMailBox(String hostname, String username, String password, String folderName, String subject) throws MessagingException, GeneralSecurityException, IOException{
        props = System.getProperties();
        props.setProperty("mail.store.protocol", "imaps");
        props.setProperty("mail.imaps.host", "imap.gmail.com");
        props.setProperty("mail.imaps.port", "993");
        props.setProperty("mail.imaps.ssl.enable", "true");
        props.put("mail.imaps.ssl.socketFactory", new MailSSLSocketFactory());
        session = Session.getInstance(props);
        store = session.getStore();
        store.connect(username, password);
        folder = store.getFolder(folderName);
        folder.open(Folder.READ_ONLY);
        messages = folder.search(getSearchTerm(subject));
        if (messages[0].isMimeType("multipart/*")){
             Multipart multipart = (Multipart) messages[0].getContent();
             for(int i=0;i<multipart.getCount();i++) {
                BodyPart bodyPart = multipart.getBodyPart(0);
                if (bodyPart.isMimeType("text/*")) {
                    msg = msg+bodyPart.getContent().toString();
                }
             }
        }else{
            msg = messages[0].getContent().toString();
        }
        System.out.println(msg);
        folder.close(true);
        store.close();
    }

     public SearchTerm getSearchTerm(String subject){
         subjectTerm = new SubjectTerm(subject);
         unseenFlagTerm = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
         recentFlagTerm; = new FlagTerm(new Flags(Flags.Flag.RECENT), true);
         return new AndTerm(subjectTerm, new AndTerm(unseenFlagTerm, recentFlagTerm));
     }
}
</code>```

答:
What mail server are you using?

Some mail servers don't implement the RECENT flag in any useful way, so messages might not be marked RECENT.  Try leaving out the RECENT term and see if you get more results.

If that doesn't help, add code to dump out the flags for all messages and then post the JavaMail debug output that shows the flags for all messages along with the search request and response.

Note also that some IMAP servers don't fully or correctly implement the SEARCH command and so can't handle the kind of search you're doing.

Finally, note that you don't need to set the socketFactory property unless you're using MailSSLSocketFactory in a more interesting way than you've show in your example code above.

Body:
I would like to fetch recent, unread emails with a specific subject in a particular folder from my gmail account. I am using JavaMail API as below but it returns 0 results. However if I just use subjectTerm alone, I see results. Please let me know where am I going wrong. Thank you.

Please note that I used  messages[0] below instead of looping through messages array for code simplicity to paste it here.

     public void openMailBox(String hostname, String username, String password, String folderName, String subject) throws MessagingException, GeneralSecurityException, IOException{
        props = System.getProperties();
        props.setProperty("mail.store.protocol", "imaps");
        props.setProperty("mail.imaps.host", "imap.gmail.com");
        props.setProperty("mail.imaps.port", "993");
        props.setProperty("mail.imaps.ssl.enable", "true");
        props.put("mail.imaps.ssl.socketFactory", new MailSSLSocketFactory());
        session = Session.getInstance(props);
        store = session.getStore();
        store.connect(username, password);
        folder = store.getFolder(folderName);
        folder.open(Folder.READ_ONLY);
        messages = folder.search(getSearchTerm(subject));
        if (messages[0].isMimeType("multipart/*")){
             Multipart multipart = (Multipart) messages[0].getContent();
             for(int i=0;i<multipart.getCount();i++) {
                BodyPart bodyPart = multipart.getBodyPart(0);
                if (bodyPart.isMimeType("text/*")) {
                    msg = msg+bodyPart.getContent().toString();
                }
             }
        }else{
            msg = messages[0].getContent().toString();
        }
        System.out.println(msg);
        folder.close(true);
        store.close();
    }

     public SearchTerm getSearchTerm(String subject){
         subjectTerm = new SubjectTerm(subject);
         unseenFlagTerm = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
         recentFlagTerm; = new FlagTerm(new Flags(Flags.Flag.RECENT), true);
         return new AndTerm(subjectTerm, new AndTerm(unseenFlagTerm, recentFlagTerm));
     }
}


问:
Best way to echo two rows of two?
I am retrievieng from a query 4 rows.

This rows recover the id (to set the href), the image path and the title.

For example the code for the first row is:

```<code><div class="row">
<div class="col">
 <a href="id">
  <img src="file">
   <p class="titulo-noticia">The title</p>
 </a>
</div>
<div class="col">
 <a href="id">
  <img src="file">
   <p class="titulo-noticia">Another title</p>
 </a>
</div>
</div>
</code>```

I achieve this using:

```<code>echo "<div class='table'>"
 for($i=0;$i<2;$i++){
  echo "<div class='row'>"
  for($j=0;$j<2;$j++){
   echo "<div class='col'>"
   echo "<a href='id'>
      <img src='file'>
       <p class='titulo-noticia'>".$title."</p>
     </a>"
   echo "</div>"
  } //end col loop
  echo "</div>"
 } //end row loop
echo "</div>"
</code>```

CSS is:

```<code>.col{
    display: table-cell;
}

.row{
    display: row;
}
.table{
    display: table;

}
</code>```

Is this the correct way to show a 2*2 matrix of php content? Or there is a better way using  css?

Thank you.

答:
You over-complicating this.

You need to do it by chunks, array_chunk() perfect for that:

```<code>foreach(array_chunk($array, 2) as $chunks){
   //<div class="row">
   foreach($chunk as $chunk){
       //<div class="col"></div>
   }
   //</div>
}
</code>```

Title: Best way to echo two rows of two?

Body:
I am retrievieng from a query 4 rows.

This rows recover the id (to set the href), the image path and the title.

For example the code for the first row is:

The title

Another title

I achieve this using:

echo "
"
 for($i=0;$i<2;$i++){
  echo "
"
  for($j=0;$j<2;$j++){
   echo "
"
   echo "

".$title."

     "
   echo "
"
  } //end col loop
  echo "
"
 } //end row loop
echo "
"

CSS is:

.col{
    display: table-cell;
}

.row{
    display: row;
}
.table{
    display: table;

}

Is this the correct way to show a 2*2 matrix of php content? Or there is a better way using  css?

Thank you.

Body:
You over-complicating this.

You need to do it by chunks, array_chunk() perfect for that:

foreach(array_chunk($array, 2) as $chunks){
   //<div class="row">
   foreach($chunk as $chunk){
       //<div class="col"></div>
   }
   //</div>
}


问:
Python Tkinter Prompt
I am trying to prompt the user to enter a string of text. Is there available with python tkinter a Javascript like prompt?</p>

答:
You can ask a yes/no question with</p>

```<code>from tkinter import *
answer = tkinter.messagebox.askquestion
</code>```

Title: Python Tkinter Prompt

Body:
You can ask a yes/no question with

from tkinter import *
answer = tkinter.messagebox.askquestion


问:
Update statement with joins
I must create migration to update question image attribute but i need to check some attributes from other tables, my schema looks like this:

```<code>question {
id,
name,
groupId,
imageUrl -> i need to update this
}

group {
id,
name,
quizId
}

quiz {
id,
name,
type -> where type is 'History'
}
</code>```

And i need to update attribute imageUrl from table question WHERE quiz type is for example 'History', i'm not sure how i can join this tables when using UPDATE. I tried something like this but it's not working like i want.

```<code>UPDATE question SET image_url = 'pathToImage' FROM quiz q WHERE q.type = 'History'
</code>```

答:
try:</p>

```<code>   with cte as (
      select q.id qid
      from question q
      join "group" g on g.id = groupId
      join quiz z on z.id = quizId
      where type = 'History'
    )
    UPDATE question q
      SET image_url = 'pathToImage'
    FROM cte.qid = q.id
</code>```

Title: Update statement with joins

Body:
I must create migration to update question image attribute but i need to check some attributes from other tables, my schema looks like this:

question {
id,
name,
groupId,
imageUrl -> i need to update this
}

group {
id,
name,
quizId
}

quiz {
id,
name,
type -> where type is 'History'
}

And i need to update attribute imageUrl from table question WHERE quiz type is for example 'History', i'm not sure how i can join this tables when using UPDATE. I tried something like this but it's not working like i want.

UPDATE question SET image_url = 'pathToImage' FROM quiz q WHERE q.type = 'History'

Body:
try:

   with cte as (
      select q.id qid
      from question q
      join "group" g on g.id = groupId
      join quiz z on z.id = quizId
      where type = 'History'
    )
    UPDATE question q
      SET image_url = 'pathToImage'
    FROM cte.qid = q.id


问:
Python prints single quotes
I have a Python project for uni which I've completed and works fine BUT it keeps printing single quotes like this:

```<code>('a', 'b') 0
('a', 'c') 1
('b', 'c') 2
('c', 'd') 0
('d', 'e') 1
('e', 'c') 3
</code>```

How do I remove them?

Those letters are the names of teams from a file,the combinations are the matches that should be played, I put them into a graph and then I did the rest of the exercise. My only problem is the quotes thing. Thanks in advance!

答:
It looks like you have built a bunch of tuples:

```<code>team1 = 'a'
team2 = 'b'
tpl = (team1, team2)
</code>```

And then printed them:

```<code>print(tpl)
</code>```

The problem is that you're getting Python's default printout behavior for the tuples. There are a bunch of alternatives for you - defining a class, and then overriding the __str__ method, for example - but what you probably want to do, in order to get things working, is just set up a more complex print command:

```<code>print("{} vs. {}".format(tpl[0], tpl[1]))
</code>```

or:

```<code>print(tpl[0], "vs.", tpl[1])
</code>```

Title: Python prints single quotes

Body:
I have a Python project for uni which I've completed and works fine BUT it keeps printing single quotes like this:

('a', 'b') 0
('a', 'c') 1
('b', 'c') 2
('c', 'd') 0
('d', 'e') 1
('e', 'c') 3

How do I remove them?

Those letters are the names of teams from a file,the combinations are the matches that should be played, I put them into a graph and then I did the rest of the exercise. My only problem is the quotes thing. Thanks in advance!

Body:
It looks like you have built a bunch of tuples:

team1 = 'a'
team2 = 'b'
tpl = (team1, team2)

And then printed them:

print(tpl)

The problem is that you're getting Python's default printout behavior for the tuples. There are a bunch of alternatives for you - defining a class, and then overriding the __str__ method, for example - but what you probably want to do, in order to get things working, is just set up a more complex print command:

print("{} vs. {}".format(tpl[0], tpl[1]))

or:

print(tpl[0], "vs.", tpl[1])


问:
Angular change detection on @Input object
I kind of understand how change detection works in Angular 2 but I'm really struggling to transfer/change my AngularJS methods over to NG2 regarding change detection.

Imagine I have a component that takes a single @Input() anObject and has a single function, logAllProperties() which, for arguments sake, logs all the properties to the console.
All I want to do is to call logAllProperties() every time anObject changes in anyway whatsoever.

I understand that treating the object as immutable (either with an external library like Immutable.js or by enforcing that the entire object changes even for a minor property change) will trigger ngOnChange but is there anyway to call a function whenever a change takes place aside from these or using DoCheck which I understand is potentially extremely inefficient.

As well as "is there a way", what is the correct way to do something like this? I'm new to Angular2 so I'm more than happy to learn the right way if Immutable and Observables are the way to go.

Thanks in advance

答:
The straightforward way of executing an action everytime anObject change is by using a setter or ngOnChange (see Fals' answer).

Using immutable objects witch a change detection strategy of OnPush is a way to improve change detection performance. This is not the most obvious use of change detection in Angular.

For a complete explanation I suggest you read this really good article and if you have some time (45 minutes) you can check this video by the author of the article here

From there, you should have a good understanding of what's going on.


问:
How do you find the roots of any polynomial?
Someone asked to solve this polynomial just for fun: x^765+x-400

This is my attempt in solving it.

```<code>m=zeros(785,1);
mtrans= m'
mtrans(1)=1;
mtrans(784)=1;
mtrans(785)=-400;
roots(mtrans)
</code>```

However I don't understand my output is it all the roots that this polynomial has? In addition, assuming that the output is a root, when I tried to plug in the numbers it does not equal to 0.

答: Use a Newton-Raphson technique. From a polynomial degree of 5, there is no analytical solution. With other words, there is no other way than using optimizer. And the land of optimizer is vast. Newton-Raphson is a very standard technique. In your case you will have n (#polynomial degree) solutions, that means you will have to seek a good one that is insensitive to your initial guess.

Body:
Someone asked to solve this polynomial just for fun: x^765+x-400

This is my attempt in solving it.

m=zeros(785,1);
mtrans= m'
mtrans(1)=1;
mtrans(784)=1;
mtrans(785)=-400;
roots(mtrans)

However I don't understand my output is it all the roots that this polynomial has? In addition, assuming that the output is a root, when I tried to plug in the numbers it does not equal to 0.


问:
moveToNext() is false
```<code>//row --> 2
int row = mCursor.getCount();
for (int i = 0; i < row; i++) {
 if (mCursor.moveToPosition(i)){
  int val = mCursor.getInt(mCursor.getColumnIndexOrThrow(UTILI_COLLOC_ID_UTILI))
 }
}
</code>```

I don't understand because I have 2 rows in my query. But when I want to read the seconde row with "mCursor.moveToPosition(i)", so it's false...Why ?

答:
You have 2 Rows : 0th & 1st . I think here your problem is because you are moving to next record in a loop & cursor already moved to last record. so it return you FALSE.

Solution: put mCursor.moveToPosition(1); out side of for loop.

Title: moveToNext() is false

Body:
//row --> 2
int row = mCursor.getCount();
for (int i = 0; i < row; i++) {
 if (mCursor.moveToPosition(i)){
  int val = mCursor.getInt(mCursor.getColumnIndexOrThrow(UTILI_COLLOC_ID_UTILI))
 }
}

I don't understand because I have 2 rows in my query. But when I want to read the seconde row with "mCursor.moveToPosition(i)", so it's false...Why ?


问:
Applying a global font to volusion template
I received a ton of help from a previous question and used:

html *
    {font-family: Helvetica !important;}

But for some reason it still doesn't change in the product descriptions. Everywhere else it is working fine. I see !important used a lot and I fear this may be the problem but the css file is massive and not designed by myself. I'm not sure what to do now.

答:
It sounds like you will need to just be more specific than the template css.

If the template css uses

```<code>h3.title { font-family: arial !important }
</code>```

You would need to use something like this to override it

```<code>.myclass h3.title { font-family: Helvetica !important }
</code>```

You could also use inline styles to get a higher specificity than styles inside a stylesheet.

Body:
It sounds like you will need to just be more specific than the template css.

If the template css uses

h3.title { font-family: arial !important }

You would need to use something like this to override it

.myclass h3.title { font-family: Helvetica !important }

You could also use inline styles to get a higher specificity than styles inside a stylesheet.


问:
Add new pages on PDF and write the same marksheet content on next pages (FPDF python)
I am making a Mark sheet software that takes input of marks and add student data on the pdf doc. page. But every time I call the function it writes content only at the documents first and others are blank.

from fpdf import FPDF
file1= FPDF()

```<code>def write_pdf(roll):
    file1.add_page()
    file1.set_font('Arial', '', 17)
    file1.set_left_margin(45)
    file1.ln(10)
    file1.write(5, roll)
    file1.output('fir_sem.pdf','f')

def onClick():
    rno='1400654070012'
    write_pdf(rno)
</code>```

I want that every time I click on the button. New page add on document and the roll written on new pages. I am new to 'fpdf'.

How can I resolve this?

答:
The output method will close the document. See documentation.
After calling output you need to create another object.

Body:
I am making a Mark sheet software that takes input of marks and add student data on the pdf doc. page. But every time I call the function it writes content only at the documents first and others are blank.

from fpdf import FPDF
file1= FPDF()

def write_pdf(roll):
    file1.add_page()
    file1.set_font('Arial', '', 17)
    file1.set_left_margin(45)
    file1.ln(10)
    file1.write(5, roll)
    file1.output('fir_sem.pdf','f')

def onClick():
    rno='1400654070012'
    write_pdf(rno)

I want that every time I click on the button. New page add on document and the roll written on new pages. I am new to 'fpdf'.

How can I resolve this?


问:
why argument random_state in cross_validation.train_test_split is integer not boolean
i need to know why argument random_state in cross_validation.train_test_split is integer not Boolean, since it's role is to flag random allocation or not?</p>

答: To expand a bit further on Kelvin's answer, if you want a random train-test split, then don't specify the random_state parameter. If you do not want a random train-test split (i.e. you want an identically-reproducible split each time), specify random_state with an integer of your choice.


问:
How do I bypass marionette issues in Robot?
I've been asked to evaluate Robotframework  and happy with what I've seen for the most part.  For it to be a viable option for me however, I need it to work in Firefox.

Marionette capabilities were a problem in my Ruby/Capybara environment, and I was able to shut it off.

```<code>Capybara.register_driver :selenium do |app|
  Capybara::Selenium::Driver.new(app, :browser => :firefox, desired_capabilities: Selenium::WebDriver::Remote::Capabilities.firefox(marionette: false))
end
</code>```

Getting the same thing in Robot / Python 2.7 / ff44.0 has generated an error in either direction.

When marionette is on:

```<code>${dc}   Evaluate    sys.modules['selenium.webdriver'].DesiredCapabilities.FIREFOX  sys, selenium.webdriver
Set To Dictionary    ${dc}    marionette=${True}
Open Browser    ${url_bck_auto}     Firefox     desired_capabilities=${dc}
</code>```

I get this:

Our products rock                                   | FAIL |
  WebDriverException: Message: Unsupported Marionette protocol version
  2, required 3

If I turn it off, gecko bumps me to ff51.0.1(32-bit) and I get a different message:

Our products rock                                   | FAIL |
  WebDriverException: Message: Can't load the profile. Possible firefox
  version mismatch. You must use GeckoDriver instead for Firefox 48+.
  Profile Dir: c:\users\blah\appdata\local\temp\tmpqzlxha\webdriver-

  py-profilecopy If you specified a log_file in the FirefoxBinary
  constructor, check it for details.

Geckodriver is version 0.15.0

Any help will be appreciated,  thanks!

答:
On Windows 10 I'm running Robot Framework 3.0, Selenium2Library 1.8.0, Selenium 3.0.2 and when I start your example, or the simplified single open browser    http://google.com I get the same result when using Gecko 0.15.0. The browser starts but does not move to the desired page. The driver closes successfully but the browser stays open.

When using the same setup, but downgrading Geckodriver to 0.14.0 the results change, and the browser behaves as expected. Loads the page and closes when Close Browser keyword is called.

So, I recommend downgrading to Geckodriver 0.14.0.

Body:
I've been asked to evaluate Robotframework  and happy with what I've seen for the most part.  For it to be a viable option for me however, I need it to work in Firefox.

Marionette capabilities were a problem in my Ruby/Capybara environment, and I was able to shut it off.

Capybara.register_driver :selenium do |app|
  Capybara::Selenium::Driver.new(app, :browser => :firefox, desired_capabilities: Selenium::WebDriver::Remote::Capabilities.firefox(marionette: false))
end

Getting the same thing in Robot / Python 2.7 / ff44.0 has generated an error in either direction.

When marionette is on:

${dc}   Evaluate    sys.modules['selenium.webdriver'].DesiredCapabilities.FIREFOX  sys, selenium.webdriver
Set To Dictionary    ${dc}    marionette=${True}
Open Browser    ${url_bck_auto}     Firefox     desired_capabilities=${dc}

I get this:

Our products rock                                   | FAIL |
  WebDriverException: Message: Unsupported Marionette protocol version
  2, required 3

If I turn it off, gecko bumps me to ff51.0.1(32-bit) and I get a different message:

Our products rock                                   | FAIL |
  WebDriverException: Message: Can't load the profile. Possible firefox
  version mismatch. You must use GeckoDriver instead for Firefox 48+.
  Profile Dir: c:\users\blah\appdata\local\temp\tmpqzlxha\webdriver-

  py-profilecopy If you specified a log_file in the FirefoxBinary
  constructor, check it for details.

Geckodriver is version 0.15.0

Any help will be appreciated,  thanks!


问:
Retrieve data from database in Laravel 5.0
I have a table in my database called modules so in my controller I write like this to retrieve datas from the table

```<code> $allModuleNames = DB::table('users')->get();
 return view("BaseView.home")->with('$allModuleNames',$allModuleNames);
</code>```

But for some weird reason I am getting syntax error, unexpected ';'  error on the query like. This must be silly I guess,not able to pass through this. Can someone help?
I have added this to the header

use Illuminate\Support\Facades\DB;

And when I hover over table I get method table not found in \illuminate\Support\Faces\DB

答:
Use modules intead of users :

```<code>$allModuleNames = DB::table('modules')->get();
</code>```

and you dont need the $ on this line :

```<code>return view("BaseView.home")->with('allModuleNames',$allModuleNames);
</code>```

Body:
I have a table in my database called modules so in my controller I write like this to retrieve datas from the table

 $allModuleNames = DB::table('users')->get();
 return view("BaseView.home")->with('$allModuleNames',$allModuleNames);

But for some weird reason I am getting syntax error, unexpected ';'  error on the query like. This must be silly I guess,not able to pass through this. Can someone help?
I have added this to the header

use Illuminate\Support\Facades\DB;

And when I hover over table I get method table not found in \illuminate\Support\Faces\DB

Body:
Use modules intead of users :

$allModuleNames = DB::table('modules')->get();

and you dont need the $ on this line :

return view("BaseView.home")->with('allModuleNames',$allModuleNames);