问:
Ember: Edit model object without setting isdirty
This topic har been discussed on stackoverflow before, but not with latest version of ember data, I think. At least none of the suggestions I have found have worked for me.

I use the latest version of Ember and Ember data (versjon 2.13.0). I use the JsonApiAdapter.

Scenario

After I load a record from the server I want to do a few changes to some of its properties. These changes shall not make the record dirty, and the changed attributes shall not show up in the record.changedAttributes(). Any changes the user may do after that shall make the record dirty.

Searching for a solution

I have tried to manually change the isDirty flag, but it didn't do it. I have also tried to find the place in the ember data code that sets the state after a record has been loaded (because essentially I am trying to do the same thing) but I haven't found where it is.
I have also tried record.send('pushedData'), but I didn't change anything of the state of the record.

Any help appreciated.

答:
I know 3 methods which allow to modify server's response without dirtying records:

You can override adapter's handleResponse method and make modifications right in payload.

You can override serializer's normalize method.

You can load records from server with Ember.$.ajax method, modify response and then pass it to store's pushPayload method.

First two methods are good if you need to modify record after every load from server (no matter from what route/controller you do it). Both adapter and serializer can be model-specific. If you need to do it in only one place (controller or route), or if you need an access to route's/controller's variables - 3rd method is good.

I'm not aware about any way to mark record as dirty/not dirty. If you modify a record after it was stored, it becomes dirty.


来源: stackexchange

问:
Creating and Updating User Table With PHP/MySql Script
I am reading a book on PHP, MYSQL, JAVASCRIPT and JQUERY.  While reading, I do type the code and see how it worked.  I have the following script which I ran to create a table named: "users', and subsequently update the table with two users.  When I ran the script in my browser, it only created the new table but failed to update it with the new users.  I do not receive any error.  Below is the entire script.

```<code><?php // setup_users.php

require_once 'login.php';

$connection = new mysqli($hn, $un, $pw, $db);
if ($connection->connect_error) die($connection->connect_error);

$query = "CREATE TABLE users (

    forename VARCHAR(32) NOT NULL,
    surname  VARCHAR(32) NOT NULL,
    username VARCHAR(32) NOT NULL UNIQUE,
    password VARCHAR(32) NOT NULL
    )";

$result = $connection->query($query);

if (!$result) die($connection->error);

$salt1 = "qm&g";
$salt2 = "ph!@";

$forename = 'Baban';
$surname = 'Sadik';
$username = 'bsadik';
$password = 'babansadik1';
$token = hash('ripemd128', "$salt1$password$salt2");

add_user($connection, $forename, $surname, $username, $token);

$forename = 'Abdullah';
$surname = 'Abubakar';
$username = 'aabubakar';
$password = 'abakar1';
$token = hash('ripemd128', "$salt1$password$salt2");

add_user($connection, $forename, $surname, $username, $token);

function add_user($connection, $fn, $sn, $un, $pw) {

    $query = "INSERT INTO users VALUES('$forename', '$surname', '$username', '$token')";
    $result = $connection->query($query);
    if (!$result) die($connection->error);

}

?>
</code>```

Where did go wrong please?

答:
Your add_user function has parameters different to what you are trying to use in the query itself.

Change the query to the following:

```<code>INSERT INTO users VALUES('$fn', '$sn', '$un', '$pw')
</code>```

Note that you should use prepared statements instead, as currently the code is susceptible to SQL Injection attacks. If the book you're using doesn't contain information on using prepared statements, scrap the book and find one that does instead.

ContentLicense: CC BY-SA 3.0

Body:
I am reading a book on PHP, MYSQL, JAVASCRIPT and JQUERY.  While reading, I do type the code and see how it worked.  I have the following script which I ran to create a table named: "users', and subsequently update the table with two users.  When I ran the script in my browser, it only created the new table but failed to update it with the new users.  I do not receive any error.  Below is the entire script.

<?php // setup_users.php

require_once 'login.php';

$connection = new mysqli($hn, $un, $pw, $db);
if ($connection->connect_error) die($connection->connect_error);

$query = "CREATE TABLE users (

    forename VARCHAR(32) NOT NULL,
    surname  VARCHAR(32) NOT NULL,
    username VARCHAR(32) NOT NULL UNIQUE,
    password VARCHAR(32) NOT NULL
    )";

$result = $connection->query($query);

if (!$result) die($connection->error);

$salt1 = "qm&g";
$salt2 = "ph!@";

$forename = 'Baban';
$surname = 'Sadik';
$username = 'bsadik';
$password = 'babansadik1';
$token = hash('ripemd128', "$salt1$password$salt2");

add_user($connection, $forename, $surname, $username, $token);

$forename = 'Abdullah';
$surname = 'Abubakar';
$username = 'aabubakar';
$password = 'abakar1';
$token = hash('ripemd128', "$salt1$password$salt2");

add_user($connection, $forename, $surname, $username, $token);

function add_user($connection, $fn, $sn, $un, $pw) {

    $query = "INSERT INTO users VALUES('$forename', '$surname', '$username', '$token')";
    $result = $connection->query($query);
    if (!$result) die($connection->error);

}

?>

Where did go wrong please?

Body:
Your add_user function has parameters different to what you are trying to use in the query itself.

Change the query to the following:

INSERT INTO users VALUES('$fn', '$sn', '$un', '$pw')

Note that you should use prepared statements instead, as currently the code is susceptible to SQL Injection attacks. If the book you're using doesn't contain information on using prepared statements, scrap the book and find one that does instead.


问:
What is the difference between encode/decode?
I've never been sure that I understand the difference between str/unicode decode and encode.

I know that str().decode() is for when you have a string of bytes that you know has a certain character encoding, given that encoding name it will return a unicode string.

I know that unicode().encode() converts unicode chars into a string of bytes according to a given encoding name.

But I don't understand what str().encode() and unicode().decode() are for. Can anyone explain, and possibly also correct anything else I've gotten wrong above?

EDIT:

Several answers give info on what .encode does on a string, but no-one seems to know what .decode does for unicode.

答:
The decode method of unicode strings really doesn't have any applications at all (unless you have some non-text data in a unicode string for some reason -- see below). It is mainly there for historical reasons, i think. In Python 3 it is completely gone.

unicode().decode() will perform an implicit encoding of s using the default (ascii) codec. Verify this like so:

```<code>>>> s = u'ö'
>>> s.decode()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 0:
ordinal not in range(128)

>>> s.encode('ascii')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 0:
ordinal not in range(128)
</code>```

The error messages are exactly the same.

For str().encode() it's the other way around -- it attempts an implicit decoding of s with the default encoding:

```<code>>>> s = 'ö'
>>> s.decode('utf-8')
u'\xf6'
>>> s.encode()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0:
ordinal not in range(128)
</code>```

Used like this, str().encode() is also superfluous.

But there is another application of the latter method that is useful: there are encodings that have nothing to do with character sets, and thus can be applied to 8-bit strings in a meaningful way:

```<code>>>> s.encode('zip')
'x\x9c;\xbc\r\x00\x02>\x01z'
</code>```

You are right, though: the ambiguous usage of "encoding" for both these applications is... awkard. Again, with separate byte and string types in Python 3, this is no longer an issue.

OwnerDisplayName: Nick

LastEditorDisplayName: Abgan

Body:
The decode method of unicode strings really doesn't have any applications at all (unless you have some non-text data in a unicode string for some reason -- see below). It is mainly there for historical reasons, i think. In Python 3 it is completely gone.

unicode().decode() will perform an implicit encoding of s using the default (ascii) codec. Verify this like so:

>>> s = u'ö'
>>> s.decode()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 0:
ordinal not in range(128)

>>> s.encode('ascii')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 0:
ordinal not in range(128)

The error messages are exactly the same.

For str().encode() it's the other way around -- it attempts an implicit decoding of s with the default encoding:

>>> s = 'ö'
>>> s.decode('utf-8')
u'\xf6'
>>> s.encode()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0:
ordinal not in range(128)

Used like this, str().encode() is also superfluous.

But there is another application of the latter method that is useful: there are encodings that have nothing to do with character sets, and thus can be applied to 8-bit strings in a meaningful way:

>>> s.encode('zip')
'x\x9c;\xbc\r\x00\x02>\x01z'

You are right, though: the ambiguous usage of "encoding" for both these applications is... awkard. Again, with separate byte and string types in Python 3, this is no longer an issue.


问:
Making a material-ui dialog draggable
I'm trying to use material-ui Dialog feature.

Dialog doc

We need to make the dialog draggable across the view port.
As per below issue, material-ui doesn't have this functionality by default.

Issue here

I tried using  react-draggable
by enclosing the dialog with the draggable component. It doesnt work. Has anyone faced this issue?

Thanks in advance

答:
SO, after a lot of tries, I gave up on material UI dialog and wrote my own modal.
react-draggable works as expected on that.</p>

Title: Making a material-ui dialog draggable


问:
Remove some part of URL using javascript
I have a URL which will be something like below

```<code>http://localhost:22306/NESSPATH/VSAT/I-HP-AAMB-ENB-0003_C1//Panaromic//120.jpg
</code>```

I want URL which will be something like this

```<code>NESSPATH/VSAT/I-HP-AAMB-ENB-0003_C1//Panaromic//120.jpg
</code>```

Here is what I get in variable

```<code>VSATSaving.PANAROMIC_120 = document.getElementById('ImgPanaromic120').src;
</code>```

how to get that using javascript. Tried with lastIndexOf but it is not working

答: window.location.pathname will give you path.

Body:
I have a URL which will be something like below

http://localhost:22306/NESSPATH/VSAT/I-HP-AAMB-ENB-0003_C1//Panaromic//120.jpg

I want URL which will be something like this

NESSPATH/VSAT/I-HP-AAMB-ENB-0003_C1//Panaromic//120.jpg

Here is what I get in variable

VSATSaving.PANAROMIC_120 = document.getElementById('ImgPanaromic120').src;

how to get that using javascript. Tried with lastIndexOf but it is not working


问:
oracle conditional where clause with filter
I have to use a conditional where clause like below one, what is the working version of this clause?</p>

```<code>AND CASE WHEN b.kurum_turu = 1
         THEN u.kod  in ('1125', '2975', '1127', '4460', '1128', '1126')
    ELSE u.kod  in ('1125', '2975')
END
</code>```

Body:
I have to use a conditional where clause like below one, what is the working version of this clause?

AND CASE WHEN b.kurum_turu = 1
         THEN u.kod  in ('1125', '2975', '1127', '4460', '1128', '1126')
    ELSE u.kod  in ('1125', '2975')
END

Body:
My aproach is this:

 AND 1 = CASE
         WHEN  b.kurum_turu = 1 AND u.kod  in ('1125', '2975', '1127', '4460', '1128', '1126') THEN 1 ELSE 1 END


问:
Download file via PHP
I'm trying to download a zip file without revealing the URL to the user. The file should only be accessible by authorized users.

Currently I'm doing this:

```<code>// check authentication and request method etc...
// ...

$file = '../../filename.zip';
$filesize = filesize($file);
header('Content-Description: File Transfer');
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: private');
header('Content-Length: ' . $filesize);
ob_clean();
flush();

echo readfile($file);

die();
</code>```

And I can see the file is downloaded somehow in the Chrome network tab (it shows in the Response tab) and ~3MB are transferred (which is the filesize), but the file isn't downloaded in the browser.

I'm doing a simple GET request, btw.

Thanks for your help,
Tobias

EDIT: Okay, apparently I also had an error on the client side and now the file is being downloaded in the browser, but it's only a 1KB zip containing Response with status: 200 OK for URL: xxx.

My request looks like this:

```<code>let headers = new Headers({'Accept': 'application/zip'});
let options = new RequestOptions({ headers: headers, responseType: ResponseContentType.Blob });
this.authHttp.post(environment.apiUrl + 'rewards/download/', data, options)
  .map(res => new Blob([res],{ type: 'application/zip' }))
  .catch((error:any) => Observable.throw(error.json().error || 'Server error'))
  .subscribe(
    data => {
      //console.log(data);
      window.location.href = window.URL.createObjectURL(data);
    },
    error => {
      console.log("Error downloading file.");
    },
    () => console.log("Download completed."));
</code>```

EDIT2: Okay, got it. Apparently I had to use .map(res => new Blob([res.json()],{ type: 'application/zip' })) in the request. Also now I'm using FileSaver.js instead of window.location, but I don't think that affected the problem.

答:
i think you just need  to redirect ur method to your physique zip file.

i mean you need just  to  add :

```<code> header("Location: $url_physique_of_ur_zip_file");
</code>```

before

ob_clean();
flush();

and replace $url_physique_of_ur_zip_file by your physique url of your file

i wish u understand me because this solution work for me

Title: Download file via PHP

Body:
I'm trying to download a zip file without revealing the URL to the user. The file should only be accessible by authorized users.

Currently I'm doing this:

// check authentication and request method etc...
// ...

$file = '../../filename.zip';
$filesize = filesize($file);
header('Content-Description: File Transfer');
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: private');
header('Content-Length: ' . $filesize);
ob_clean();
flush();

echo readfile($file);

die();

And I can see the file is downloaded somehow in the Chrome network tab (it shows in the Response tab) and ~3MB are transferred (which is the filesize), but the file isn't downloaded in the browser.

I'm doing a simple GET request, btw.

Thanks for your help,
Tobias

EDIT: Okay, apparently I also had an error on the client side and now the file is being downloaded in the browser, but it's only a 1KB zip containing Response with status: 200 OK for URL: xxx.

My request looks like this:

let headers = new Headers({'Accept': 'application/zip'});
let options = new RequestOptions({ headers: headers, responseType: ResponseContentType.Blob });
this.authHttp.post(environment.apiUrl + 'rewards/download/', data, options)
  .map(res => new Blob([res],{ type: 'application/zip' }))
  .catch((error:any) => Observable.throw(error.json().error || 'Server error'))
  .subscribe(
    data => {
      //console.log(data);
      window.location.href = window.URL.createObjectURL(data);
    },
    error => {
      console.log("Error downloading file.");
    },
    () => console.log("Download completed."));

EDIT2: Okay, got it. Apparently I had to use .map(res => new Blob([res.json()],{ type: 'application/zip' })) in the request. Also now I'm using FileSaver.js instead of window.location, but I don't think that affected the problem.

Body:
i think you just need  to redirect ur method to your physique zip file.

i mean you need just  to  add :

 header("Location: $url_physique_of_ur_zip_file");

before

ob_clean();
flush();

and replace $url_physique_of_ur_zip_file by your physique url of your file

i wish u understand me because this solution work for me


问:
Filter Firebase Database DataSnapshot children on Android
I want to query the data from Firebase on Android.
And this is my data

And this is my Android Studio code :

```<code>Firebase myFirebaseRef = new Firebase("https://....../myCoffee/"+phone+"");
            myFirebaseRef.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot snapshot) {
                    int size= (int) snapshot.getChildrenCount();
                    txtMyCoffee.setText(""+size);
                          }
                @Override
                public void onCancelled(FirebaseError firebaseError) {
                }
            });
</code>```

Question :  The total count of the children is 4. How would I filter the children to only count children whose "coffeeNo" is "Acoffee"?

答:
```<code>Firebase myFirebaseRef = new Firebase("https://....../myCoffee/"+phone+"");
        myFirebaseRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
                int count=0;
                for(DataSnapshot item: dataSnapshot.getChildren())
                {
                         String coffeeNo=item.child("coffeeNo").toString();
                         if(coffeeNo.equals("Acofee")
                              count+=1;
                }
            @Override
            public void onCancelled(FirebaseError firebaseError) {
            }
        });
</code>```

<p>Try something like this </p>

Body:
I want to query the data from Firebase on Android.
And this is my data

And this is my Android Studio code :

Firebase myFirebaseRef = new Firebase("https://....../myCoffee/"+phone+"");
            myFirebaseRef.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot snapshot) {
                    int size= (int) snapshot.getChildrenCount();
                    txtMyCoffee.setText(""+size);
                          }
                @Override
                public void onCancelled(FirebaseError firebaseError) {
                }
            });

Question :  The total count of the children is 4. How would I filter the children to only count children whose "coffeeNo" is "Acoffee"?

Body:
Firebase myFirebaseRef = new Firebase("https://....../myCoffee/"+phone+"");
        myFirebaseRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
                int count=0;
                for(DataSnapshot item: dataSnapshot.getChildren())
                {
                         String coffeeNo=item.child("coffeeNo").toString();
                         if(coffeeNo.equals("Acofee")
                              count+=1;
                }
            @Override
            public void onCancelled(FirebaseError firebaseError) {
            }
        });

Try something like this


问:
How to avoid duplicate values in the output of v-for loop in vuejs
I want to remove or filter out the duplicate values in the output of my v-for loop. So, that 'John' appears only once instead of appearing twice in the output. Is that possible to do in vuejs ?

JS

```<code>var app = new Vue({
             el: "#app",
             data: function () {
                     return {
                       searchFields: ['number', 'name'],
                       search: '',
                       items: [
                               { name: 'Mary'},
                               { name: 'John'},
                               { name: 'John'},
                               { name: 'William'}
                             ]
                      };
             }
});
</code>```

Codepen

答:
I used a computed value, as suggested by the Vuejs guide:
https://v2.vuejs.org/v2/guide/list.html#Displaying-Filtered-Sorted-Results

```<code>computed: {
    uniqueNames: function() {
      var filtered_array = [];
      for(var i =0; i < this.items.length; i++) {
        if(filtered_array.indexOf(this.items[i].name) === -1) {
          filtered_array.push(this.items[i].name)
        }
      }
    return filtered_array;
    }
  }
</code>```

With this v-for:

```<code>v-for="name in uniqueNames"
</code>```

See my codepen

Body:
I want to remove or filter out the duplicate values in the output of my v-for loop. So, that 'John' appears only once instead of appearing twice in the output. Is that possible to do in vuejs ?

JS

var app = new Vue({
             el: "#app",
             data: function () {
                     return {
                       searchFields: ['number', 'name'],
                       search: '',
                       items: [
                               { name: 'Mary'},
                               { name: 'John'},
                               { name: 'John'},
                               { name: 'William'}
                             ]
                      };
             }
});

Codepen

Body:
I used a computed value, as suggested by the Vuejs guide:
https://v2.vuejs.org/v2/guide/list.html#Displaying-Filtered-Sorted-Results

computed: {
    uniqueNames: function() {
      var filtered_array = [];
      for(var i =0; i < this.items.length; i++) {
        if(filtered_array.indexOf(this.items[i].name) === -1) {
          filtered_array.push(this.items[i].name)
        }
      }
    return filtered_array;
    }
  }

With this v-for:

v-for="name in uniqueNames"

See my codepen

ContentLicense: CC BY-SA 4.0


问:
Finding all permutations of numbers plucked from an array which sum to 16
I would like to find all the permutations of plucking 3, 4 or 5 numbers from [2,3,4,5,6,7,8], repeats allowed, such that their sum is 16. So [8,5,3], [8,3,5] and [4,3,3,3,3] are valid permutations. Also circular permutations should be removed so [3,3,3,3,4] wouldn't also be added to the answer.
I can do this in Ruby without allowing repeats like this:

```<code>d = [2,3,4,5,6,7,8]
number_of_divisions = [3,4,5]
number_of_divisions.collect do |n|
  d.permutation(n).to_a.reject do |p|
    p[0..n].inject(0) { |sum,x| sum + x } != 16
  end
end
</code>```

How could I allow repeats so that [3,3,3,3,4] was included?

答:
For all permutations, including duplicates, one might use Array#repeated_permutation:

```<code>d = [2,3,4,5,6,7,8]
number_of_divisions = [3,4,5]
number_of_divisions.flat_map do |n|
  d.repeated_permutation(n).reject do |p| # no need `to_a`
    p.inject(:+) != 16
  end
end
</code>```

or, even better with Array#repeated_combination:

```<code>number_of_divisions.flat_map do |n|
  d.repeated_combination(n).reject do |p| # no need `to_a`
    p.inject(:+) != 16
  end
end
</code>```

Body:
I would like to find all the permutations of plucking 3, 4 or 5 numbers from [2,3,4,5,6,7,8], repeats allowed, such that their sum is 16. So [8,5,3], [8,3,5] and [4,3,3,3,3] are valid permutations. Also circular permutations should be removed so [3,3,3,3,4] wouldn't also be added to the answer.
I can do this in Ruby without allowing repeats like this:

d = [2,3,4,5,6,7,8]
number_of_divisions = [3,4,5]
number_of_divisions.collect do |n|
  d.permutation(n).to_a.reject do |p|
    p[0..n].inject(0) { |sum,x| sum + x } != 16
  end
end

How could I allow repeats so that [3,3,3,3,4] was included?

Body:
For all permutations, including duplicates, one might use Array#repeated_permutation:

d = [2,3,4,5,6,7,8]
number_of_divisions = [3,4,5]
number_of_divisions.flat_map do |n|
  d.repeated_permutation(n).reject do |p| # no need `to_a`
    p.inject(:+) != 16
  end
end

or, even better with Array#repeated_combination:

number_of_divisions.flat_map do |n|
  d.repeated_combination(n).reject do |p| # no need `to_a`
    p.inject(:+) != 16
  end
end


问:
Is there a way to add a class to the component root element?
Except for adding the class in html.

I mean something like that:

In html

```<code><my-component></my-component>
</code>```

In js

```<code>angular.module('app').component('myComponent', {
  template: '<div class="inner-element">Inner element</div>',
  className: 'outer-element' <--- wanted property
});
</code>```

This is how I want it to look after render:

```<code><my-component class="outer-element"> <--- that's what I want to get
  <div class="inner-element">Inner element</div>
</my-component>
</code>```

答:
You could specify controller that adds class on component init

```<code>controller: function($element) {
  this.$onInit = function() {
    $element.addClass('outer-element')
  };
}
</code>```

But this kinda goes against encapsulation and such.

Body:
Except for adding the class in html.

I mean something like that:

In html

<my-component></my-component>

In js

angular.module('app').component('myComponent', {
  template: '
Inner element
',
  className: 'outer-element' <--- wanted property
});

This is how I want it to look after render:

<my-component class="outer-element"> <--- that's what I want to get

Inner element

</my-component>

Body:
You could specify controller that adds class on component init

controller: function($element) {
  this.$onInit = function() {
    $element.addClass('outer-element')
  };
}

But this kinda goes against encapsulation and such.


问:
problem regarding crystal reports
Actually when I drag fields from a database onto a report and when I run the report, only the first row data is shown i.e. if CourseID field is dragged onto a report and when I run it should show CourseID1 and below it CourseID2. But, it shows only CourseID1. I know it is a silly thing, but as I'm new to crystal reports, I'm unable to solve it. So, please help me out...thanks in advance...</p>

答: You have to first make a table on the report, then drag the desired fields into the table headers.</p>

ContentLicense: CC BY-SA 2.5

Title: problem regarding crystal reports


问:
Combining 2 lists and and remove duplicates .Output in a third list .My attempts do not work
I always seem to have a problem when I need to compare 2 list and produce a 3rd list which include all unique items.I need to perform this quite often.

Attempt to reproduce the issue with a noddy example.

Am I missing something?
Thanks for any suggestions

The wanted result

```<code>   Name= Jo1 Surname= Bloggs1 Category= Account
   Name= Jo2 Surname= Bloggs2 Category= Sales
   Name= Jo5 Surname= Bloggs5 Category= Development
   Name= Jo6 Surname= Bloggs6 Category= Management
   Name= Jo8 Surname= Bloggs8 Category= HR
   Name= Jo7 Surname= Bloggs7 Category= Cleaning

class Program
{
    static void Main(string[] args)
    {
          List<Customer> listOne = new List<Customer>();
        List<Customer> listTwo = new List<Customer>();

        listOne.Add(new Customer { Category = "Account", Name = "Jo1", Surname = "Bloggs1" });
        listOne.Add(new Customer { Category = "Sales", Name = "Jo2", Surname = "Bloggs2" });
        listOne.Add(new Customer { Category = "Development", Name = "Jo5", Surname = "Bloggs5" });
        listOne.Add(new Customer { Category = "Management", Name = "Jo6", Surname = "Bloggs6" });

        listTwo.Add(new Customer { Category = "HR", Name = "Jo8", Surname = "Bloggs8" });
        listTwo.Add(new Customer { Category = "Sales", Name = "Jo2", Surname = "Bloggs2" });
        listTwo.Add(new Customer { Category = "Management", Name = "Jo6", Surname = "Bloggs6" });
        listTwo.Add(new Customer { Category = "Development", Name = "Jo5", Surname = "Bloggs5" });
        listTwo.Add(new Customer { Category = "Cleaning", Name = "Jo7", Surname = "Bloggs7" });

    List<Customer> resultList = listOne.Union(listTwo).ToList();//**I get duplicates why????**

        resultList.ForEach(customer => Console.WriteLine("Name= {0} Surname= {1} Category= {2}", customer.Name, customer.Surname, customer.Category));
        Console.Read();

        IEnumerable<Customer> resultList3 = listOne.Except(listTwo);//**Does not work**

        foreach (var customer in resultList3)
        {
            Console.WriteLine("Name= {0} Surname= {1} Category= {2}", customer.Name, customer.Surname, customer.Category);
        }

        **//Does not work**
        var resultList2 = (listOne
                       .Where(n => !(listTwo
                           .Select(o => o.Category))
                           .Contains(n.Category)))
                       .OrderBy(n => n.Category);

        foreach (var customer in resultList2)
        {
            Console.WriteLine("Name= {0}
                             Surname= {1}
                             Category= {2}",
</code>```

customer.Name,
customer.Surname,
customer.Category);
            }
            Console.Read();

```<code>  }
}

public class Customer
{
    public string Name { get; set; }
    public string Surname { get; set; }
    public string Category { get; set; }
}
</code>```

答:
I had a similar problem where I had two very large lists with random strings.

I made a recursive function which returns a new list with unique strings. I compared two lists with 100k random strings(it may or may not exist duplicates) each with 6 characters of abcdefghijklmnopqrstuvwxyz1234567890 and it was done in about 230 ms. I only measured the given function.

I hope this will give value to someone.

Image of test run

```<code>makeCodesUnique(List<string> existing, List<string> newL)
{
    // Get all duplicate between two lists
    List<string> duplicatesBetween = newL.Intersect(existing).ToList();

    // Get all duplicates within list
    List<string> duplicatesWithin = newL.GroupBy(x => x)
    .Where(group => group.Count() > 1)
    .Select(group => group.Key).ToList();

    if (duplicatesBetween.Count == 0 && duplicatesWithin.Count == 0)
    {
        // Return list if there are no duplicates
        return newL;
    }
    else
    {
        if (duplicatesBetween.Count != 0)
        {
            foreach (string duplicateCode in duplicatesBetween)
            {
                newL.Remove(duplicateCode);
            }

            // Generate new codes to substitute the removed ones
            List<string> newCodes = generateSomeMore(duplicatesBetween.Count);
            newL.AddRange(newCodes);
            makeCodesUnique(existing, newL);
        }
        else if (duplicatesWithin.Count != 0)
        {
            foreach (string duplicateCode in duplicatesWithin)
            {
                newL.Remove(duplicateCode);
            }
            List<string> newCodes = generateSomeMore(duplicatesWithin.Count);
            new.AddRange(newCodes);
            makeCodesUnique(existing, newL);
        }
    }
    return newL;
}
</code>```

Body:
I always seem to have a problem when I need to compare 2 list and produce a 3rd list which include all unique items.I need to perform this quite often.

Attempt to reproduce the issue with a noddy example.

Am I missing something?
Thanks for any suggestions

The wanted result

   Name= Jo1 Surname= Bloggs1 Category= Account
   Name= Jo2 Surname= Bloggs2 Category= Sales
   Name= Jo5 Surname= Bloggs5 Category= Development
   Name= Jo6 Surname= Bloggs6 Category= Management
   Name= Jo8 Surname= Bloggs8 Category= HR
   Name= Jo7 Surname= Bloggs7 Category= Cleaning

class Program
{
    static void Main(string[] args)
    {
          List<Customer> listOne = new List<Customer>();
        List<Customer> listTwo = new List<Customer>();

        listOne.Add(new Customer { Category = "Account", Name = "Jo1", Surname = "Bloggs1" });
        listOne.Add(new Customer { Category = "Sales", Name = "Jo2", Surname = "Bloggs2" });
        listOne.Add(new Customer { Category = "Development", Name = "Jo5", Surname = "Bloggs5" });
        listOne.Add(new Customer { Category = "Management", Name = "Jo6", Surname = "Bloggs6" });

        listTwo.Add(new Customer { Category = "HR", Name = "Jo8", Surname = "Bloggs8" });
        listTwo.Add(new Customer { Category = "Sales", Name = "Jo2", Surname = "Bloggs2" });
        listTwo.Add(new Customer { Category = "Management", Name = "Jo6", Surname = "Bloggs6" });
        listTwo.Add(new Customer { Category = "Development", Name = "Jo5", Surname = "Bloggs5" });
        listTwo.Add(new Customer { Category = "Cleaning", Name = "Jo7", Surname = "Bloggs7" });

    List<Customer> resultList = listOne.Union(listTwo).ToList();//**I get duplicates why????**

        resultList.ForEach(customer => Console.WriteLine("Name= {0} Surname= {1} Category= {2}", customer.Name, customer.Surname, customer.Category));
        Console.Read();

        IEnumerable<Customer> resultList3 = listOne.Except(listTwo);//**Does not work**

        foreach (var customer in resultList3)
        {
            Console.WriteLine("Name= {0} Surname= {1} Category= {2}", customer.Name, customer.Surname, customer.Category);
        }

        **//Does not work**
        var resultList2 = (listOne
                       .Where(n => !(listTwo
                           .Select(o => o.Category))
                           .Contains(n.Category)))
                       .OrderBy(n => n.Category);

        foreach (var customer in resultList2)
        {
            Console.WriteLine("Name= {0}
                             Surname= {1}
                             Category= {2}",

customer.Name,
customer.Surname,
customer.Category);
            }
            Console.Read();

  }
}

public class Customer
{
    public string Name { get; set; }
    public string Surname { get; set; }
    public string Category { get; set; }
}

Body:
I had a similar problem where I had two very large lists with random strings.

I made a recursive function which returns a new list with unique strings. I compared two lists with 100k random strings(it may or may not exist duplicates) each with 6 characters of abcdefghijklmnopqrstuvwxyz1234567890 and it was done in about 230 ms. I only measured the given function.

I hope this will give value to someone.

Image of test run

makeCodesUnique(List<string> existing, List<string> newL)
{
    // Get all duplicate between two lists
    List<string> duplicatesBetween = newL.Intersect(existing).ToList();

    // Get all duplicates within list
    List<string> duplicatesWithin = newL.GroupBy(x => x)
    .Where(group => group.Count() > 1)
    .Select(group => group.Key).ToList();

    if (duplicatesBetween.Count == 0 && duplicatesWithin.Count == 0)
    {
        // Return list if there are no duplicates
        return newL;
    }
    else
    {
        if (duplicatesBetween.Count != 0)
        {
            foreach (string duplicateCode in duplicatesBetween)
            {
                newL.Remove(duplicateCode);
            }

            // Generate new codes to substitute the removed ones
            List<string> newCodes = generateSomeMore(duplicatesBetween.Count);
            newL.AddRange(newCodes);
            makeCodesUnique(existing, newL);
        }
        else if (duplicatesWithin.Count != 0)
        {
            foreach (string duplicateCode in duplicatesWithin)
            {
                newL.Remove(duplicateCode);
            }
            List<string> newCodes = generateSomeMore(duplicatesWithin.Count);
            new.AddRange(newCodes);
            makeCodesUnique(existing, newL);
        }
    }
    return newL;
}


问:
QT Application segmentation fault on exit when using std::unique_ptr for the QMainWindow
I should clarify first, my question is, why does the segfault happen in the case where I use a std::unique_ptr but it doesn't when I change the code to use new and delete? I don't really have an issue here, since the segfault is fixed and I know I'm properly cleaning things up with new and delete. I just want to know why I couldn't use a std::unique_ptr.

If I create my QMainWindow instance in a std::unique_ptr and my MainWindow creates a child window (e.g. opening a QComboBox or ToolTip), my application will segfault on exit. In this case, if my MainWindow does not create any child windows, there is no segfault.

If I manage my QMainWindow instance myself with new and delete, there is no segfault regardless of whether or not I create a child window.

This is my main, it simply calls run on my Bridge class that handles creating the instance of my MainWindow class and starting it.

```<code>int main(int argc, char *argv[])
{
    Bridge bridge(argc, argv);
    bridge.run(); // Handles starting the main window
}
</code>```

This is a shortened version of my Bridge class that results in a segfault (using std::unique_ptr I get a segfault on exit):

```<code>class Bridge::IMPL {
public:
    IMPL(int& argc, char ** argv) :
        mainwindow(), isRunning(true), app(argc, argv) {}
    ~IMPL() = default;
public:
    std::unique_ptr<MainWindow> mainwindow;
    bool isRunning;
    QApplication app;
};

Bridge::Bridge(int& argc, char ** argv) :
    pImpl(make_unique<IMPL>(argc, argv)) {

    pImpl->mainwindow.reset(new MainWindow(this));
}
</code>```

This is the Bridge class with no segfault (slightly modified to remove the std::unique_ptr and instead use new and delete. This version of the Bridge class DOES NOT CRASH):

```<code>class Bridge::IMPL {
public:
    IMPL(int& argc, char ** argv) :
        mainwindow(nullptr), isRunning(true), app(argc, argv) {}
    ~IMPL() {
        if (mainwindow) {
            delete mainwindow;
        }
    }
public:
    MainWindow* mainwindow;
    bool isRunning;
    QApplication app;
};

Bridge::Bridge(int& argc, char ** argv) :
    pImpl(make_unique<IMPL>(argc, argv)) {

    pImpl->mainwindow= new MainWindow(this);
}
</code>```

This is the back-trace when a segfault would happen:

Also there is a weird print-out about QBasicTimer that doesn't get printed after I changed the code to use new and delete instead of std::unique_ptr

```<code>QBasicTimer::start: QBasicTimer can only be used with threads started with QThread

Thread 1 "application" received signal SIGSEGV, Segmentation fault.
0x00007fffe75bf2e2 in ?? () from /home/user/Qt/5.9/gcc_64/plugins/platforms/../../lib/libQt5XcbQpa.so.5
(gdb) bt
#0  0x00007fffe75bf2e2 in ?? () from /home/user/Qt/5.9/gcc_64/plugins/platforms/../../lib/libQt5XcbQpa.so.5
#1  0x00007fffe75bf5c4 in ?? () from /home/user/Qt/5.9/gcc_64/plugins/platforms/../../lib/libQt5XcbQpa.so.5
#2  0x00007fffe75b9669 in QXcbConnection::removeWindowEventListener(unsigned int) () from /home/user/Qt/5.9/gcc_64/plugins/platforms/../../lib/libQt5XcbQpa.so.5
#3  0x00007fffe75ceafa in QXcbWindow::destroy() () from /home/user/Qt/5.9/gcc_64/plugins/platforms/../../lib/libQt5XcbQpa.so.5
#4  0x00007fffe75cec07 in QXcbWindow::~QXcbWindow() () from /home/user/Qt/5.9/gcc_64/plugins/platforms/../../lib/libQt5XcbQpa.so.5
#5  0x00007fffe43ce2ee in ?? () from /home/user/Qt/5.9/gcc_64/plugins/xcbglintegrations/libqxcb-glx-integration.so
#6  0x00007ffff4b56f46 in QWindowPrivate::destroy() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Gui.so.5
#7  0x00007ffff534ecd7 in QWidgetPrivate::deleteTLSysExtra() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#8  0x00007ffff53524d8 in QWidget::destroy(bool, bool) () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#9  0x00007ffff53598b0 in QWidget::~QWidget() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#10 0x00007ffff541ae7a in ?? () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#11 0x00007ffff4580b83 in QObjectPrivate::deleteChildren() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Core.so.5
#12 0x00007ffff5359894 in QWidget::~QWidget() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#13 0x00007ffff540eac9 in QComboBox::~QComboBox() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#14 0x00007ffff4580b83 in QObjectPrivate::deleteChildren() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Core.so.5
#15 0x00007ffff5359894 in QWidget::~QWidget() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#16 0x00007ffff5359ab9 in QWidget::~QWidget() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#17 0x00007ffff4580b83 in QObjectPrivate::deleteChildren() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Core.so.5
#18 0x00007ffff5359894 in QWidget::~QWidget() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#19 0x00007ffff5359ab9 in QWidget::~QWidget() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#20 0x00007ffff4580b83 in QObjectPrivate::deleteChildren() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Core.so.5
#21 0x00007ffff5359894 in QWidget::~QWidget() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#22 0x0000000000421ed4 in MainWindow::~MainWindow() ()
#23 0x0000000000421f0e in MainWindow::~MainWindow() ()
#24 0x0000000000421698 in std::default_delete<MainWindow>::operator()(MainWindow*) const ()
#25 0x0000000000421171 in std::unique_ptr<MainWindow, std::default_delete<MainWindow> >::~unique_ptr() ()
#26 0x000000000042191c in Bridge::IMPL::~IMPL() ()
#27 0x0000000000421942 in std::default_delete<Bridge::IMPL>::operator()(Bridge::IMPL*) const ()
#28 0x0000000000421387 in std::unique_ptr<Bridge::IMPL, std::default_delete<Bridge::IMPL> >::~unique_ptr() ()
#29 0x0000000000420cb0 in Bridge::~Bridge() ()
#30 0x0000000000421c41 in main ()
</code>```

It should also be noted that this QApplication is run using a while loop and calls to app.processEvents() rather than calling exec(). I realize that's not the best way to do it, however this app is part of another application that polls for events from somewhere else and since the nature of this application is more "proof-of-concept" than anything else, I wanted to keep it simple by having it all in one thread. See below for a snippet of my run method:

```<code>while (isRunning()) {
    poller.poll(25);
    app.processEvents();
}
</code>```

EDIT:

In my constructor for MainWindow the this I'm passing is not being set as the parent (the parent is nullptr):

header:

```<code>class MainWindow: public QMainWindow
{
    Q_OBJECT
public:
    class BridgeInterface{
    public:
        // Some pure virtual methods here
    };

    explicit MainWindow(BridgeInterface* interface, QWidget* parent = nullptr);

// some more stuff...

private:
    class IMPL;
    std::unique_ptr<IMPL> pImpl;
};
</code>```

source:

```<code>MainWindow::MainWindow(BridgeInterface* interface, QWidget* parent) :
    QMainWindow(parent), pImpl(make_unique<IMPL>()) {

    pImpl->ui->setupUi(this);
    pImpl->bridgeInterface = interface;

    // Connect slots and stuff
}
</code>```

答:
Difficult to tell for sure given you did not post code for MainWindow but I'd say you are deleting mainwindow twice.

pImpl->mainwindow= new MainWindow(this); if this is a parent it will delete MainWindow automatically upon destruction and same thing will do the unique_ptr

Either use raw pointers and rely on Qt's parent-child cleanup or use smart pointers and do not pass a parent to MainWindow

Body:
I should clarify first, my question is, why does the segfault happen in the case where I use a std::unique_ptr but it doesn't when I change the code to use new and delete? I don't really have an issue here, since the segfault is fixed and I know I'm properly cleaning things up with new and delete. I just want to know why I couldn't use a std::unique_ptr.

If I create my QMainWindow instance in a std::unique_ptr and my MainWindow creates a child window (e.g. opening a QComboBox or ToolTip), my application will segfault on exit. In this case, if my MainWindow does not create any child windows, there is no segfault.

If I manage my QMainWindow instance myself with new and delete, there is no segfault regardless of whether or not I create a child window.

This is my main, it simply calls run on my Bridge class that handles creating the instance of my MainWindow class and starting it.

int main(int argc, char *argv[])
{
    Bridge bridge(argc, argv);
    bridge.run(); // Handles starting the main window
}

This is a shortened version of my Bridge class that results in a segfault (using std::unique_ptr I get a segfault on exit):

class Bridge::IMPL {
public:
    IMPL(int& argc, char ** argv) :
        mainwindow(), isRunning(true), app(argc, argv) {}
    ~IMPL() = default;
public:
    std::unique_ptr<MainWindow> mainwindow;
    bool isRunning;
    QApplication app;
};

Bridge::Bridge(int& argc, char ** argv) :
    pImpl(make_unique<IMPL>(argc, argv)) {

    pImpl->mainwindow.reset(new MainWindow(this));
}

This is the Bridge class with no segfault (slightly modified to remove the std::unique_ptr and instead use new and delete. This version of the Bridge class DOES NOT CRASH):

class Bridge::IMPL {
public:
    IMPL(int& argc, char ** argv) :
        mainwindow(nullptr), isRunning(true), app(argc, argv) {}
    ~IMPL() {
        if (mainwindow) {
            delete mainwindow;
        }
    }
public:
    MainWindow* mainwindow;
    bool isRunning;
    QApplication app;
};

Bridge::Bridge(int& argc, char ** argv) :
    pImpl(make_unique<IMPL>(argc, argv)) {

    pImpl->mainwindow= new MainWindow(this);
}

This is the back-trace when a segfault would happen:

Also there is a weird print-out about QBasicTimer that doesn't get printed after I changed the code to use new and delete instead of std::unique_ptr

QBasicTimer::start: QBasicTimer can only be used with threads started with QThread

Thread 1 "application" received signal SIGSEGV, Segmentation fault.
0x00007fffe75bf2e2 in ?? () from /home/user/Qt/5.9/gcc_64/plugins/platforms/../../lib/libQt5XcbQpa.so.5
(gdb) bt
#0  0x00007fffe75bf2e2 in ?? () from /home/user/Qt/5.9/gcc_64/plugins/platforms/../../lib/libQt5XcbQpa.so.5
#1  0x00007fffe75bf5c4 in ?? () from /home/user/Qt/5.9/gcc_64/plugins/platforms/../../lib/libQt5XcbQpa.so.5
#2  0x00007fffe75b9669 in QXcbConnection::removeWindowEventListener(unsigned int) () from /home/user/Qt/5.9/gcc_64/plugins/platforms/../../lib/libQt5XcbQpa.so.5
#3  0x00007fffe75ceafa in QXcbWindow::destroy() () from /home/user/Qt/5.9/gcc_64/plugins/platforms/../../lib/libQt5XcbQpa.so.5
#4  0x00007fffe75cec07 in QXcbWindow::~QXcbWindow() () from /home/user/Qt/5.9/gcc_64/plugins/platforms/../../lib/libQt5XcbQpa.so.5
#5  0x00007fffe43ce2ee in ?? () from /home/user/Qt/5.9/gcc_64/plugins/xcbglintegrations/libqxcb-glx-integration.so
#6  0x00007ffff4b56f46 in QWindowPrivate::destroy() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Gui.so.5
#7  0x00007ffff534ecd7 in QWidgetPrivate::deleteTLSysExtra() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#8  0x00007ffff53524d8 in QWidget::destroy(bool, bool) () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#9  0x00007ffff53598b0 in QWidget::~QWidget() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#10 0x00007ffff541ae7a in ?? () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#11 0x00007ffff4580b83 in QObjectPrivate::deleteChildren() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Core.so.5
#12 0x00007ffff5359894 in QWidget::~QWidget() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#13 0x00007ffff540eac9 in QComboBox::~QComboBox() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#14 0x00007ffff4580b83 in QObjectPrivate::deleteChildren() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Core.so.5
#15 0x00007ffff5359894 in QWidget::~QWidget() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#16 0x00007ffff5359ab9 in QWidget::~QWidget() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#17 0x00007ffff4580b83 in QObjectPrivate::deleteChildren() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Core.so.5
#18 0x00007ffff5359894 in QWidget::~QWidget() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#19 0x00007ffff5359ab9 in QWidget::~QWidget() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#20 0x00007ffff4580b83 in QObjectPrivate::deleteChildren() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Core.so.5
#21 0x00007ffff5359894 in QWidget::~QWidget() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#22 0x0000000000421ed4 in MainWindow::~MainWindow() ()
#23 0x0000000000421f0e in MainWindow::~MainWindow() ()
#24 0x0000000000421698 in std::default_delete<MainWindow>::operator()(MainWindow*) const ()
#25 0x0000000000421171 in std::unique_ptr<MainWindow, std::default_delete<MainWindow> >::~unique_ptr() ()
#26 0x000000000042191c in Bridge::IMPL::~IMPL() ()
#27 0x0000000000421942 in std::default_delete<Bridge::IMPL>::operator()(Bridge::IMPL*) const ()
#28 0x0000000000421387 in std::unique_ptr<Bridge::IMPL, std::default_delete<Bridge::IMPL> >::~unique_ptr() ()
#29 0x0000000000420cb0 in Bridge::~Bridge() ()
#30 0x0000000000421c41 in main ()

It should also be noted that this QApplication is run using a while loop and calls to app.processEvents() rather than calling exec(). I realize that's not the best way to do it, however this app is part of another application that polls for events from somewhere else and since the nature of this application is more "proof-of-concept" than anything else, I wanted to keep it simple by having it all in one thread. See below for a snippet of my run method:

while (isRunning()) {
    poller.poll(25);
    app.processEvents();
}

EDIT:

In my constructor for MainWindow the this I'm passing is not being set as the parent (the parent is nullptr):

header:

class MainWindow: public QMainWindow
{
    Q_OBJECT
public:
    class BridgeInterface{
    public:
        // Some pure virtual methods here
    };

    explicit MainWindow(BridgeInterface* interface, QWidget* parent = nullptr);

// some more stuff...

private:
    class IMPL;
    std::unique_ptr<IMPL> pImpl;
};

source:

MainWindow::MainWindow(BridgeInterface* interface, QWidget* parent) :
    QMainWindow(parent), pImpl(make_unique<IMPL>()) {

    pImpl->ui->setupUi(this);
    pImpl->bridgeInterface = interface;

    // Connect slots and stuff
}


问:
Deployment and USB device issue
I am using my physical Android device to do the deployment of my project. After I moved the folder to a new location in my computer, I am since unable to select(or even view) my device from the emulator list.

Now I try to run the app on the emulator, which after building gives this error:

It also gives a red line under this piece of code:

```<code>public App()
{
      **InitializeComponent();**

      MainPage = new LoginSystem.MainPage();
}
</code>```

The "Quick Actions" tool tells me that - "The name 'InitializeComponent' does not exist in the current context."

If I remove the initialize component line, I am able to build and deploy my project. However, i really need that line of code. How can I fix it?

UPDATE

After following the link suggested by PiLHA - getting an error on InitializeComponent() on xaml.cs files

I am able to build the project and deploy it, however, i get a new error:

And I am still not able to get the USB connected device to show up in the emulator's list.

I am assuming that there is a problem with the debugger, that is causing the error and not showing the USB device. I have researched quite a bit, yet no solid solution. Please help.

UPDATE 2

I have set my device to allow for debugging. I had been using this device for this purpose before, it's just that this is a new obstacle is am facing at the moment.

答:
I had the same issue where even after enabling USB debugging, my physical device wouldn't show up in the list. Here is the solution I found:

Open storage settings.

Click on the three dots on the right side and select USB computer connection.

Uncheck and check the mass storage option.

Your device should now show up in the list.

Title: Deployment and USB device issue

Body:
I am using my physical Android device to do the deployment of my project. After I moved the folder to a new location in my computer, I am since unable to select(or even view) my device from the emulator list.

Now I try to run the app on the emulator, which after building gives this error:

It also gives a red line under this piece of code:

public App()
{
      **InitializeComponent();**

      MainPage = new LoginSystem.MainPage();
}

The "Quick Actions" tool tells me that - "The name 'InitializeComponent' does not exist in the current context."

If I remove the initialize component line, I am able to build and deploy my project. However, i really need that line of code. How can I fix it?

UPDATE

After following the link suggested by PiLHA - getting an error on InitializeComponent() on xaml.cs files

I am able to build the project and deploy it, however, i get a new error:

And I am still not able to get the USB connected device to show up in the emulator's list.

I am assuming that there is a problem with the debugger, that is causing the error and not showing the USB device. I have researched quite a bit, yet no solid solution. Please help.

UPDATE 2

I have set my device to allow for debugging. I had been using this device for this purpose before, it's just that this is a new obstacle is am facing at the moment.


问:
VBA (excel 2010) if error (like #N/A) then move to next row
Experts!

I am trying to automate a manual process and am running into (I'm sure) an easy fix. There are about 8 columns that may contain the results of an index/match formula that I need to copy into column B. For example, Column 'A' is an IP address, and column 'B' needs to have a value from one of the columns "C" through "K". The logic needs to first look in 'K' then move descending towards 'C', checking if the value is first an error (like #N/A or 0). If no error exists then copy that value into a summary sheet. I think my real obstacle is that I cannot get the logic right to check for an error. It either does nothing (which I suspect I am just exiting the loop) or it just copies everything regardless. Assistance is greatly appreciated!

```<code>Sub MakeSummary()
    Dim oRng1 As Range, oRng2 As Range
    Dim oWS1 As Worksheet, oWS2 As Worksheet, i As Long

    ' Initial cell to check
    Set oWS1 = ThisWorkbook.Worksheets("Master")
    Set oRng1 = oWS1.Range("A1")

    ' Initial cell to store
    Set oWS2 = ThisWorkbook.Worksheets("Summary")
    Set oRng2 = oWS2.Range("A1")

    ' Clear original data on Summary
    i = 0
    Do Until IsEmpty(oRng2.Offset(i, 0))
        oRng2.Offset(i, 0).EntireRow.ClearContents
        i = i + 1
    Loop

    ' Look for IPs on "Master", then put in to "Summary"
    ' If value in cell is #N/A or 0, then skip to next cell

    Do Until IsEmpty(oRng1)
                If oRng1.Value = Application.WorksheetFunction.IsNA(oRng1.Formula) Then
                Set oRng2 = oRng2.Offset(0, 1)
                Else
                oRng2.Value = oRng1.Offset(0, 1).Value ' IPs
                oRng2.Offset(0, 1).Value = oRng1.Offset(0, 2).Value ' 1st Match
                oRng2.Offset(0, 2).Value = oRng1.Offset(0, 3).Value ' 2nd Match
                Set oRng2 = oRng2.Offset(1, 0) ' Move to next row to store

        Set oRng1 = oRng1.Offset(1, 0) ' Move to next row to check

    Loop

    ' Clean up
    Set oRng1 = Nothing
    Set oWS1 = Nothing
    Set oRng2 = Nothing
    Set oWS2 = Nothing
End Sub
</code>```

答:
You can use Application.WorksheetFunction.IsError to check the formula result to see if it is an error.  In which case your code would look like this (edited to make use of the IsError() function mentioned in the comments

```<code>    Sub MakeSummary2()

    Dim oRng1 As Range
    Dim oRng2 As Range
    Dim oWS1 As Worksheet
    Dim oWS2 As Worksheet
    Dim X As Integer

    ' Initial cell to check
    Set oWS1 = ThisWorkbook.Worksheets("Master")
    Set oRng1 = oWS1.Range("A2")

    ' Initial cell to store
    Set oWS2 = ThisWorkbook.Worksheets("Summary")
    Set oRng2 = oWS2.Range("A2")

    ' Clear original data on Summary

    oWS2.Cells.Clear

    ' Look for IPs on "Master", then put in to "Summary"
    ' If value in cell is #N/A or 0, then skip to next cell

    Do Until IsEmpty(oRng1)
        If IsError(oRng1.Offset(0, 1).Value) Then
            For X = 10 To 2 Step -1
                If Not IsError(oRng1.Offset(0, X).Value) Then
                    If oRng1.Offset(0, X).Value <> "" Or oRng1.Offset(0, X).Value <> 0 Then
                        oRng2.Value = oRng1.Value
                        oRng2.Offset(0, 1).Value = oRng1.Offset(0, X).Value
                        Set oRng2 = oRng2.Offset(1, 0)
                        Exit For
                    End If
                End If
            Next X
            If X = 1 And oRng2.Value = "" Then
                oRng2.Value = oRng1.Value
                oRng2.Offset(0, 1).Value = "No Data"
                Set oRng2 = oRng2.Offset(1, 0)
            End If
        Else
            oRng2.Value = oRng1.Value
            oRng2.Offset(0, 1).Value = oRng1.Offset(0, X).Value
            Set oRng2 = oRng2.Offset(1, 0)
        End If
        Set oRng1 = oRng1.Offset(1, 0) ' Move to next row to check
    Loop
End Sub
</code>```

This will place the value of "No Data" in column B in the event that all of the data in columns C:K are either errors, empty, or 0's

Body:
Experts!

I am trying to automate a manual process and am running into (I'm sure) an easy fix. There are about 8 columns that may contain the results of an index/match formula that I need to copy into column B. For example, Column 'A' is an IP address, and column 'B' needs to have a value from one of the columns "C" through "K". The logic needs to first look in 'K' then move descending towards 'C', checking if the value is first an error (like #N/A or 0). If no error exists then copy that value into a summary sheet. I think my real obstacle is that I cannot get the logic right to check for an error. It either does nothing (which I suspect I am just exiting the loop) or it just copies everything regardless. Assistance is greatly appreciated!

Sub MakeSummary()
    Dim oRng1 As Range, oRng2 As Range
    Dim oWS1 As Worksheet, oWS2 As Worksheet, i As Long

    ' Initial cell to check
    Set oWS1 = ThisWorkbook.Worksheets("Master")
    Set oRng1 = oWS1.Range("A1")

    ' Initial cell to store
    Set oWS2 = ThisWorkbook.Worksheets("Summary")
    Set oRng2 = oWS2.Range("A1")

    ' Clear original data on Summary
    i = 0
    Do Until IsEmpty(oRng2.Offset(i, 0))
        oRng2.Offset(i, 0).EntireRow.ClearContents
        i = i + 1
    Loop

    ' Look for IPs on "Master", then put in to "Summary"
    ' If value in cell is #N/A or 0, then skip to next cell

    Do Until IsEmpty(oRng1)
                If oRng1.Value = Application.WorksheetFunction.IsNA(oRng1.Formula) Then
                Set oRng2 = oRng2.Offset(0, 1)
                Else
                oRng2.Value = oRng1.Offset(0, 1).Value ' IPs
                oRng2.Offset(0, 1).Value = oRng1.Offset(0, 2).Value ' 1st Match
                oRng2.Offset(0, 2).Value = oRng1.Offset(0, 3).Value ' 2nd Match
                Set oRng2 = oRng2.Offset(1, 0) ' Move to next row to store

        Set oRng1 = oRng1.Offset(1, 0) ' Move to next row to check

    Loop

    ' Clean up
    Set oRng1 = Nothing
    Set oWS1 = Nothing
    Set oRng2 = Nothing
    Set oWS2 = Nothing
End Sub

Body:
You can use Application.WorksheetFunction.IsError to check the formula result to see if it is an error.  In which case your code would look like this (edited to make use of the IsError() function mentioned in the comments

    Sub MakeSummary2()

    Dim oRng1 As Range
    Dim oRng2 As Range
    Dim oWS1 As Worksheet
    Dim oWS2 As Worksheet
    Dim X As Integer

    ' Initial cell to check
    Set oWS1 = ThisWorkbook.Worksheets("Master")
    Set oRng1 = oWS1.Range("A2")

    ' Initial cell to store
    Set oWS2 = ThisWorkbook.Worksheets("Summary")
    Set oRng2 = oWS2.Range("A2")

    ' Clear original data on Summary

    oWS2.Cells.Clear

    ' Look for IPs on "Master", then put in to "Summary"
    ' If value in cell is #N/A or 0, then skip to next cell

    Do Until IsEmpty(oRng1)
        If IsError(oRng1.Offset(0, 1).Value) Then
            For X = 10 To 2 Step -1
                If Not IsError(oRng1.Offset(0, X).Value) Then
                    If oRng1.Offset(0, X).Value <> "" Or oRng1.Offset(0, X).Value <> 0 Then
                        oRng2.Value = oRng1.Value
                        oRng2.Offset(0, 1).Value = oRng1.Offset(0, X).Value
                        Set oRng2 = oRng2.Offset(1, 0)
                        Exit For
                    End If
                End If
            Next X
            If X = 1 And oRng2.Value = "" Then
                oRng2.Value = oRng1.Value
                oRng2.Offset(0, 1).Value = "No Data"
                Set oRng2 = oRng2.Offset(1, 0)
            End If
        Else
            oRng2.Value = oRng1.Value
            oRng2.Offset(0, 1).Value = oRng1.Offset(0, X).Value
            Set oRng2 = oRng2.Offset(1, 0)
        End If
        Set oRng1 = oRng1.Offset(1, 0) ' Move to next row to check
    Loop
End Sub

This will place the value of "No Data" in column B in the event that all of the data in columns C:K are either errors, empty, or 0's


问:
Loop list while adding to it
I've built my system in c-sharp (winforms) and I've run into a problem. In my view - my graphical interface - I'm starting a pretty heavy algorithm, which in each loop adds a result to a list in my view. The algorithm runs in a presenter (MVP pattern), using a backgroundworker - enabling the view not to freeze. As I said before, the algorithm runs in a loop, and since it's so heavy, I want to process the results of the algorithm as they come in.

View:

```<code>...
public List<string> Results { get; }
...
_presenter.RunAlgorithmAsync();
//Start processing results
...
</code>```

Backgroundworker in presenter:

```<code>...
_view.Results.Add(result);
...
</code>```

To sum it up, how can I start processing the list while the backgroundworker adds to it? Of course, the backgroundworker can work faster than the processing of the list, and vice versa - the processing may have to wait for results to arrive to the list, and the list need to be able up build up a stack of results.

I realize this question may be blurry, but if you ask me questions, I'm sure I can define the problem better.

答: Is it something that you can use the ObservableCollection and catch the CollectionChanged event to catch and process each item as it's added to the collection?

Title: Loop list while adding to it

Body:
I've built my system in c-sharp (winforms) and I've run into a problem. In my view - my graphical interface - I'm starting a pretty heavy algorithm, which in each loop adds a result to a list in my view. The algorithm runs in a presenter (MVP pattern), using a backgroundworker - enabling the view not to freeze. As I said before, the algorithm runs in a loop, and since it's so heavy, I want to process the results of the algorithm as they come in.

View:

...
public List<string> Results { get; }
...
_presenter.RunAlgorithmAsync();
//Start processing results
...

Backgroundworker in presenter:

...
_view.Results.Add(result);
...

To sum it up, how can I start processing the list while the backgroundworker adds to it? Of course, the backgroundworker can work faster than the processing of the list, and vice versa - the processing may have to wait for results to arrive to the list, and the list need to be able up build up a stack of results.

I realize this question may be blurry, but if you ask me questions, I'm sure I can define the problem better.


问:
How to append a custom created plugin to existing plugins in TinyMCE editor using Javascript
I have created a new plugin for social sharing purpose. I need to append this plugin in TinyMCE editor. i.e, my new plugin need to appear in one of the toolbars along with plugins like 'Bold,Italic' etc. Please help me to resolve this issue as early as possible.</p>

答:
The process for creating a plugin is documented here:

https://www.tinymce.com/docs/advanced/creating-a-plugin/

What specific issue are you having that the documentation does not cover?


问:
Why does spark-ml ALS model returns NaN and negative numbers predictions?
Actually I'm trying to use ALS from spark-ml with implicit ratings.

I noticed that some predictions given by my trained model are negative or NaN, why is it?

答:
Apache Spark provides an option to force non negative constraints on ALS.

Thus, to remove these negative values, you'll just need to set :

Python:

```<code>nonnegative=True
</code>```

Scala:

```<code>setNonnegative(true)
</code>```

when creating your ALS model, i.e :

```<code>>>> als = ALS(rank=10, maxIter=5, seed=0, nonnegative=True)
</code>```

Non-negative matrix factorization (NMF or NNMF), also called non-negative matrix approximation is a group of algorithms in multivariate analysis and linear algebra where a matrix V is factorized into (usually) two matrices W and H, with the property that all three matrices have nonnegative elements [Ref. Wikipedia].

If you want to read more about NMF , I'd recommend reading the following paper :

Collaborative Filtering via Ensembles of Matrix
Factorizations

As for NaN values, usually it's due to splitting your dataset which can lead to unseen items or users if one of them isn't present in the training set and for the matter just present in the testing set. This might also happen if you cross validated your training. For the matter, there is a couple of JIRAs that are marked resolved for 2.2 :

https://issues.apache.org/jira/browse/SPARK-14489.

https://issues.apache.org/jira/browse/SPARK-19345.

The latest will allow you set the cold start strategy to use when creating your model.

Body:
Apache Spark provides an option to force non negative constraints on ALS.

Thus, to remove these negative values, you'll just need to set :

Python:

nonnegative=True

Scala:

setNonnegative(true)

when creating your ALS model, i.e :

>>> als = ALS(rank=10, maxIter=5, seed=0, nonnegative=True)

Non-negative matrix factorization (NMF or NNMF), also called non-negative matrix approximation is a group of algorithms in multivariate analysis and linear algebra where a matrix V is factorized into (usually) two matrices W and H, with the property that all three matrices have nonnegative elements [Ref. Wikipedia].

If you want to read more about NMF , I'd recommend reading the following paper :

Collaborative Filtering via Ensembles of Matrix
Factorizations

As for NaN values, usually it's due to splitting your dataset which can lead to unseen items or users if one of them isn't present in the training set and for the matter just present in the testing set. This might also happen if you cross validated your training. For the matter, there is a couple of JIRAs that are marked resolved for 2.2 :

https://issues.apache.org/jira/browse/SPARK-14489.

https://issues.apache.org/jira/browse/SPARK-19345.

The latest will allow you set the cold start strategy to use when creating your model.


问:
javascript help me fix my first hands on code
help me fix this, simple convert to roman numerals code. with two input box, first where i input a number, 2nd box where the result will be shown. and a submit button

result wont show up on 2nd box after hitting convert/submit button

js code:

    function toRoman(){
 var num = document.getElementById('num').value;
 var result = "";
 var db = { 'M':1000, 'CM':900,'D':500,'CD':400, 'C':100, 'XC':90, 'L':50, 'XL':40, 'X':10, 'IX':9, 'V':5, 'IV':4, 'I':1 };
 for(var i in db){
  var m = parseInt(num/db[i]);
  result = i.repeat(m);
  num = num%db[i];
 }
 return result;
 document.getElementById('result').value = result;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
    <body>

    <label for="num">Number</label><br/>
    <input type="Number" name="num" id="num"><br/><br/>
    <label for="result">Result</label><br/>
    <textarea id="result" name="result"></textarea><br/><br/>
    <input type="submit" id="submit" value="Convert!" onclick="toRoman()">

    <script src="toRoman.js"></script>
    </body>
    </code>```

答:
change:

```<code>return result;
document.getElementById('result');
</code>```

to

```<code>document.getElementById('result').innerHTML = result;
</code>```

Body:
help me fix this, simple convert to roman numerals code. with two input box, first where i input a number, 2nd box where the result will be shown. and a submit button

result wont show up on 2nd box after hitting convert/submit button

js code:

    function toRoman(){
 var num = document.getElementById('num').value;
 var result = "";
 var db = { 'M':1000, 'CM':900,'D':500,'CD':400, 'C':100, 'XC':90, 'L':50, 'XL':40, 'X':10, 'IX':9, 'V':5, 'IV':4, 'I':1 };
 for(var i in db){
  var m = parseInt(num/db[i]);
  result = i.repeat(m);
  num = num%db[i];
 }
 return result;
 document.getElementById('result').value = result;
    }

    Number

    <input type="Number" name="num" id="num">

    Result

    <textarea id="result" name="result"></textarea>

    <input type="submit" id="submit" value="Convert!" onclick="toRoman()">

Body:
change:

return result;
document.getElementById('result');

to

document.getElementById('result').innerHTML = result;


问:
Sed move a line
I just need to move a line up in sed. I can select the line with

```<code>sed -i '7s///'
</code>```

I need to move line 7 up 2 lines so it will be line 5.

I can't find anything on the internet to do this without complicated scripts, I can't find a simple solution of moving a specific line a specific number of times.

答:
```<code>seq 10|sed '5{N;h;d};7G'
</code>```

when up to line 5 append next line(line 6) into pattern space then save them into hold space and delete them from pattern space; up to line 7 then append the hold space content("5\n6") behind the line 7; now, pattern space is "7\n5\n6";finally,sed will print the pattern space at the end of current cycle by default(if no "-n" parameter)

Title: Sed move a line

Body:
I just need to move a line up in sed. I can select the line with

sed -i '7s///'

I need to move line 7 up 2 lines so it will be line 5.

I can't find anything on the internet to do this without complicated scripts, I can't find a simple solution of moving a specific line a specific number of times.

Body:
seq 10|sed '5{N;h;d};7G'

when up to line 5 append next line(line 6) into pattern space then save them into hold space and delete them from pattern space; up to line 7 then append the hold space content("5\n6") behind the line 7; now, pattern space is "7\n5\n6";finally,sed will print the pattern space at the end of current cycle by default(if no "-n" parameter)


问:
Resource merging in Instant Apps features modules
In an Instant App feature module, I'm importing an aar (using "api" statement from a maven repository) which contains an activity declaration in its manifest and a "style" resource used in this declaration.
The resulting manifest merging fails because the style resource is not found in the base feature project.
It seems resources from imported aar in features modules are not included in the base feature module.

Since the plugin is still in alpha mode I'm not sure if I'm doing something wrong, if it is a bug or the expected behaviour.

Any advice on this?

答:
Actually it seems that for now this is the intended behaviour.
They now affirmn in the official FAQ:
"In addition, all the resources referenced by the manifest of a feature module must be present in the base feature module. "

In case such as the one described it that can be troublesome because either you are forced to include the library providing the resources in the base module or at least redeclare in the base module (trough overriding), resources used in the manifest.

Source: https://developer.android.com/topic/instant-apps/faqs.html


问:
Do virtual pages reside only in storage? And what is virtual memory without storage?
Principles of virtual memory

This figure shows pages being stored in disk and page frames in ram. If there's no swap area, then there would be no pages and only page frames. In the absence of the swap area how virtual addresses are translated? What will the page table store, they're no pages essentially?

A related question here:

The selected answer says:

Frame or page frame is basically a physical page which is a chunk of memory in main memory while page or virtual page is yet to be mapped to a page frame in main memory.

Do virtual pages reside only disk? And if there's no swap area, are there pages at all? The answer says pages are mapped to page frames through a page table, but doesn't mention where do these pages exist or what if there's no swap area.

What is virtual memory if there's no swap area and only ram? A typical virtual memory is disk + ram. What if there there's no disk in that expression?

答:
That diagram is highly confusing because it is showing two concepts at once: Logical memory translation and virtual memory—AND it is splitting the two concepts apart, rather than conflating them as was the norm in the old days.

What will the page table store, they're no pages essentially?

The page table defines the logical address space. It identifies which pages are in the address space. Such pages may or may not exist in physical memory.

In the absence of the swap area how virtual addresses are translated?

Entirely using the page table. If the system uses paging, the operating system has to implement a second level of translation to locate where a specific page is located in secondary storage.

What is virtual memory if there's no swap area and only ram? A typical virtual memory is disk + ram. What if there there's no disk in that expression?

Then you have logical memory translation without virtual memory.


问:
how to do addition In Sql Server using dynamic generated field?
I have table called "Cart". Fields are :

CartId

ClientId

ProductId

Qty

Now i am joining this table with ProductMaster to get ProductName and ProuctPrice

```<code>select cc.CartId,cc.ProductId,pm.ProductName,cc.Qty,
        (pm.ProductPrice * cc.Qty) As SubTotal
from ClientCart as cc
    inner join ProductMaster as pm on cc.ProductId = pm.ProductId
</code>```

Now I want to genrate GrandTotal using dynamic field SubTotal. How Can i do this?

答:
Try this:</p>

```<code>select subtable.CartId, sum(subtable.SubTotal)
from (
select cc.CartId,cc.ProductId,pm.ProductName,cc.Qty,
        (pm.ProductPrice * cc.Qty) As SubTotal
from ClientCart as cc
inner join ProductMaster as pm on cc.ProductId = pm.ProductId
where cc.ClientId = @id ) subtable
group by subtable.CartId;
</code>```

Body:
I have table called "Cart". Fields are :

CartId

ClientId

ProductId

Qty

Now i am joining this table with ProductMaster to get ProductName and ProuctPrice

select cc.CartId,cc.ProductId,pm.ProductName,cc.Qty,
        (pm.ProductPrice * cc.Qty) As SubTotal
from ClientCart as cc
    inner join ProductMaster as pm on cc.ProductId = pm.ProductId

Now I want to genrate GrandTotal using dynamic field SubTotal. How Can i do this?

Body:
Try this:

select subtable.CartId, sum(subtable.SubTotal)
from (
select cc.CartId,cc.ProductId,pm.ProductName,cc.Qty,
        (pm.ProductPrice * cc.Qty) As SubTotal
from ClientCart as cc
inner join ProductMaster as pm on cc.ProductId = pm.ProductId
where cc.ClientId = @id ) subtable
group by subtable.CartId;


问:
MySQL field default value not applied on join
I've written a CREATE statement with -1 default value for some INT fields :

```<code>CREATE TABLE IF NOT EXISTS table (
    country_id INT(11) NOT NULL DEFAULT -1,
    ...)
</code>```

When making a join with UPDATE, the non-matching values are replaced by 0, instead of -1 as I expected :

```<code> UPDATE table AS t1
SET
    t1.country_id = (SELECT
            t2.id
        FROM
            country AS t2
        WHERE
            t1.country = t2.country
            );
</code>```

=> When the UPDATE doesnt find a match, country_id is set to 0 instead of -1

Any idea on how to get the correct behaviour ?

答:
I would suggest that you write the query as:

```<code>UPDATE table t1 JOIN
       country t2
       ON t1.country = t2.country
    SET t1.country_id = t2.id;
</code>```

But I do agree that your code should work, inserting the explicit default value when the subquery has no match.

Body:
I've written a CREATE statement with -1 default value for some INT fields :

CREATE TABLE IF NOT EXISTS table (
    country_id INT(11) NOT NULL DEFAULT -1,
    ...)

When making a join with UPDATE, the non-matching values are replaced by 0, instead of -1 as I expected :

 UPDATE table AS t1
SET
    t1.country_id = (SELECT
            t2.id
        FROM
            country AS t2
        WHERE
            t1.country = t2.country
            );

=> When the UPDATE doesnt find a match, country_id is set to 0 instead of -1

Any idea on how to get the correct behaviour ?

Body:
I would suggest that you write the query as:

UPDATE table t1 JOIN
       country t2
       ON t1.country = t2.country
    SET t1.country_id = t2.id;

But I do agree that your code should work, inserting the explicit default value when the subquery has no match.


问:
How to sort matrix column values then rows?
For example this matrix:

```<code>3 2
2 2
1 2
</code>```

Writed as this:

```<code>IEnumerable<IEnumerable<int>> inputRows = ...;
</code>```

Must become:

```<code>1 2
2 2
2 3
</code>```

So, all biggest numbers will be concentrated in the down right corner.
First, I need to sort column numbers (not entire columns), which is pretty easy to do:

```<code>var result = inputRows.Select(x=> x.OrderBy(y=>y));
</code>```

After this step matrix will become:

```<code>2 3
2 2
1 2
</code>```

But how do I sort out entire rows with LINQ?

PS Im not interested in fixed arrays solutions.

答:
You will need a row comparer. We'll keep in mind that all rows have same length:

```<code>public class RowComparer : IComparer<IEnumerable<int>>
{
    public int Compare(IEnumerable<int> x, IEnumerable<int> y)
    {
        // TODO: throw ArgumentNullException
        return x.Zip(y, (xItem, yItem) => xItem.CompareTo(yItem))
                .Where(c => c != 0).FirstOrDefault();
    }
}
</code>```

And use it for sorting:

```<code>inputRows.Select(r => r.OrderBy(x => x)).OrderBy(r => r, new RowComparer())
</code>```

Output for your sample:

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

Body:
For example this matrix:

3 2
2 2
1 2

Writed as this:

IEnumerable<IEnumerable<int>> inputRows = ...;

Must become:

1 2
2 2
2 3

So, all biggest numbers will be concentrated in the down right corner.
First, I need to sort column numbers (not entire columns), which is pretty easy to do:

var result = inputRows.Select(x=> x.OrderBy(y=>y));

After this step matrix will become:

2 3
2 2
1 2

But how do I sort out entire rows with LINQ?

PS Im not interested in fixed arrays solutions.

Body:
You will need a row comparer. We'll keep in mind that all rows have same length:

public class RowComparer : IComparer<IEnumerable<int>>
{
    public int Compare(IEnumerable<int> x, IEnumerable<int> y)
    {
        // TODO: throw ArgumentNullException
        return x.Zip(y, (xItem, yItem) => xItem.CompareTo(yItem))
                .Where(c => c != 0).FirstOrDefault();
    }
}

And use it for sorting:

inputRows.Select(r => r.OrderBy(x => x)).OrderBy(r => r, new RowComparer())

Output for your sample:

[
  [ 1, 2 ],
  [ 2, 2 ],
  [ 2, 3 ]
]


问:
Property [ptitle] does not exist on this collection instance in Laravel 5
I have a table with full of created products and when I click one of products' edit button, I get this error message: Property [ptitle] does not exist on this collection instance (View: C:\xampp\htdocs\webshop\resources\views\admin\termekszerk.blade.php)
Can anyone help me to solve this, please?
Models:

```<code>class Category extends Model
{

protected $fillable = ['cid', 'cname'];
protected $primaryKey = 'cid';

 public function item()
{
    return $this->hasMany('App\Item', 'cid');
}
}

class Item extends Model
{
protected $fillable = ['pid', 'pcat', 'pdescription', 'ptitle', 'pdb', 'par', 'pcikkszam' ];
protected $primaryKey = 'pid';

public function category()
{
    return $this->belongsTo('App\Category', 'pcat');
}

}
</code>```

Controller:

```<code>public function pedit($pid)
{
    $product = Item::find($pid)->first();
    return view('admin.termekszerk', compact('product'));
}

public function pupdate(ProductFormRequest $request, $pid)
{
    $product = Item::find($pid)->first();
    $product->ptitle = $request->get('ptitle');
    $product->pcat = $request->get('pcat');
    $product->pcikkszam = $request->get('pcikkszam');
    $product->par = $request->get('par');
    $product->pdb = $request->get('pdb');
    $product->pdescription = $request->get('pdescription');

    $product->save();
    return redirect(action('CategoriesController@index', $product->pid))->with('status', 'A termék frissítve!');

}
</code>```

termekszerk blade (this is the page what does not show when I click before edit button):

```<code><div class="container">
    <div class="well well bs-component">

        <form class="form-horizontal" method="post">

            @foreach ($errors->all() as $error)
                <p class="alert alert-danger">{{ $error }}</p>
            @endforeach

            <input type="hidden" name="_token" value="{!! csrf_token() !!}">

            <fieldset>
                <legend>Termék szerkesztése</legend>
                <div class="form-group">
                    <label for="title" class="col-lg-2 control-label">Termék neve</label>
                    <div class="col-lg-10">
                        <input type="text" class="form-control" id="ptitle" name="ptitle" value="{!! $product->ptitle !!}">
                    </div>
                </div>
                <div class="form-group">
                    <label for="title" class="col-lg-2 control-label">Cikkszám</label>
                    <div class="col-lg-10">
                        <input type="text" class="form-control" id="pcikkszam" name="pcikkszam" value="{!! $product->pcikkszam !!}">
                    </div>
                </div>
                <div class="form-group">
                    <label for="title" class="col-lg-2 control-label">Termék ára</label>
                    <div class="col-lg-10">
                        <input type="text" class="form-control" id="par" name="par" value="{!! $product->par !!}">
                    </div>
                </div>
                <div class="form-group">
                    <label for="title" class="col-lg-2 control-label">Mennyiség</label>
                    <div class="col-lg-10">
                        <input type="text" class="form-control" id="pdb" name="pdb" value="{!! $product->pdb !!}">
                    </div>
                </div>
                <div class="form-group">
                    <label for="content" class="col-lg-2 control-label">Termék leírás</label>
                    <div class="col-lg-10">
                        <textarea class="form-control" rows="18" id="pdescription" name="pdescription">{!! $product->pdescription !!}</textarea>
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-lg-10 col-lg-offset-2">
                        <a href="/admin/create_products"><button class="btn btn-default pbtn">Mégsem</button></a>

                         <form method="post" action="{!! action('CategoriesController@pupdate', $product->pid) !!}">
                            <input type="hidden" name="_token" value="{!! csrf_token() !!}">

                            <button type="submit" class="btn btn-primary pbtn">Változtatás</button>
                        </form>

                        <form method="post" action="{!! action('CategoriesController@pdestroy', $product->pid) !!}">
                            <input type="hidden" name="_token" value="{!! csrf_token() !!}">

                            <button type="submit" class="btn btn-danger pull-right pbtn">Törlés</button>
                        </form>

                    </div>
                </div>
            </fieldset>
        </form>

    </div>
</div>
</code>```

答:
I saw some shouldn't in your codes maybe correcting them will solve your problem

first in your controller:

```<code>public function pedit($pid)
{
    $product = Item::find($pid)->first();
    return view('admin.termekszerk', compact('product'));
}
</code>```

you use find method and I am not sure $pid is PK in your table structure

and you use first() method after find; its not needed because find method will get one row

for example if your table is like this

table:

-id (auto increamnet)

-pid

when you use find($pid) this search in id column and find just one row

so you can change your code like this:

```<code>public function pedit($pid)
{
    $product = Item::where('pid',$pid)->first();
    return view('admin.termekszerk', compact('product'));
}
</code>```

But If pid is PK in you table so you should remove first() method after find

secound :

I dont know why you use {!! !!} in your blade

you should use {{ }} instead of that in your blade normally

but if you store data as HTML code you can use {!! !!} to get HTML codes

Displaying Unescaped Data

By default, Blade {{ }} statements are automatically sent through
  PHP's htmlspecialchars function to prevent XSS attacks. If you do not
  want your data to be escaped, you may use the following syntax:

Body:
I have a table with full of created products and when I click one of products' edit button, I get this error message: Property [ptitle] does not exist on this collection instance (View: C:\xampp\htdocs\webshop\resources\views\admin\termekszerk.blade.php)
Can anyone help me to solve this, please?
Models:

class Category extends Model
{

protected $fillable = ['cid', 'cname'];
protected $primaryKey = 'cid';

 public function item()
{
    return $this->hasMany('App\Item', 'cid');
}
}

class Item extends Model
{
protected $fillable = ['pid', 'pcat', 'pdescription', 'ptitle', 'pdb', 'par', 'pcikkszam' ];
protected $primaryKey = 'pid';

public function category()
{
    return $this->belongsTo('App\Category', 'pcat');
}

}

Controller:

public function pedit($pid)
{
    $product = Item::find($pid)->first();
    return view('admin.termekszerk', compact('product'));
}

public function pupdate(ProductFormRequest $request, $pid)
{
    $product = Item::find($pid)->first();
    $product->ptitle = $request->get('ptitle');
    $product->pcat = $request->get('pcat');
    $product->pcikkszam = $request->get('pcikkszam');
    $product->par = $request->get('par');
    $product->pdb = $request->get('pdb');
    $product->pdescription = $request->get('pdescription');

    $product->save();
    return redirect(action('CategoriesController@index', $product->pid))->with('status', 'A termék frissítve!');

}

termekszerk blade (this is the page what does not show when I click before edit button):

        <form class="form-horizontal" method="post">

            @foreach ($errors->all() as $error)

{{ $error }}

            @endforeach

            <input type="hidden" name="_token" value="{!! csrf_token() !!}">

            <fieldset>
                <legend>Termék szerkesztése</legend>

                    Termék neve

                        <input type="text" class="form-control" id="ptitle" name="ptitle" value="{!! $product->ptitle !!}">

                    Cikkszám

                        <input type="text" class="form-control" id="pcikkszam" name="pcikkszam" value="{!! $product->pcikkszam !!}">

                    Termék ára

                        <input type="text" class="form-control" id="par" name="par" value="{!! $product->par !!}">

                    Mennyiség

                        <input type="text" class="form-control" id="pdb" name="pdb" value="{!! $product->pdb !!}">

                    Termék leírás

                        <textarea class="form-control" rows="18" id="pdescription" name="pdescription">{!! $product->pdescription !!}</textarea>

                        <button class="btn btn-default pbtn">Mégsem</button>

                         <form method="post" action="{!! action('CategoriesController@pupdate', $product->pid) !!}">
                            <input type="hidden" name="_token" value="{!! csrf_token() !!}">

                            <button type="submit" class="btn btn-primary pbtn">Változtatás</button>
                        </form>

                        <form method="post" action="{!! action('CategoriesController@pdestroy', $product->pid) !!}">
                            <input type="hidden" name="_token" value="{!! csrf_token() !!}">

                            <button type="submit" class="btn btn-danger pull-right pbtn">Törlés</button>
                        </form>

            </fieldset>
        </form>

Body:
I saw some shouldn't in your codes maybe correcting them will solve your problem

first in your controller:

public function pedit($pid)
{
    $product = Item::find($pid)->first();
    return view('admin.termekszerk', compact('product'));
}

you use find method and I am not sure $pid is PK in your table structure

and you use first() method after find; its not needed because find method will get one row

for example if your table is like this

table:

-id (auto increamnet)

-pid

when you use find($pid) this search in id column and find just one row

so you can change your code like this:

public function pedit($pid)
{
    $product = Item::where('pid',$pid)->first();
    return view('admin.termekszerk', compact('product'));
}

But If pid is PK in you table so you should remove first() method after find

secound :

I dont know why you use {!! !!} in your blade

you should use {{ }} instead of that in your blade normally

but if you store data as HTML code you can use {!! !!} to get HTML codes

Displaying Unescaped Data

By default, Blade {{ }} statements are automatically sent through
  PHP's htmlspecialchars function to prevent XSS attacks. If you do not
  want your data to be escaped, you may use the following syntax:


问:
<XSL:for-each> skip nodes with specific values
Still having a hard time grasping some of the harder templates any help would be great.

Right now I am using a simple for-each loop that sorts and shows the data in a table. I want to do the same thing but skip over all the nodes where "State" is = to "Talking Out" below is my current style sheet and below that is my XML. I was thinking I could add a for-each inside of the current loop that ignores the nodes that meet my criteria. I am escaping single quotes since it is part of a larger php script.

```<code><?xml version="1.0" encoding="ISO-8859-1"?>

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
  <html>
  <body>
    <table cellpadding="3" cellspacing="0" width="390">
      <tr>
        <th style="text-align:left;"><span style="font:20px arial; font-weight:bold;">Agent Name</span></th>
        <th style="text-align:center;"><span style="font:20px arial; font-weight:bold;">State</span></th>
        <th style="text-align:center;"><span style="font:20px arial; font-weight:bold;">Time</span></th>
      </tr>
      <xsl:for-each select="NewDataSet/AgentSales">
<tr>
 <xsl:if test="(position() mod 2 = 1)">
    <xsl:attribute name="bgcolor">#cccccc</xsl:attribute>
    </xsl:if>

 <xsl:if test="AgentSales[State=\'Talking Out\']">

    </xsl:if>

        <td style="text-align:left;"><span style="font:14px arial; font-weight:bold;"><xsl:value-of select="AgentName"/></span></td>
        <td style="text-align:center;"><span style="font:14px arial; font-weight:bold;"><xsl:value-of select="State"/></span></td>
    <td style="text-align:center;"><span style="font:14px arial; font-weight:bold;"><xsl:value-of select="time"/></span></td>
</tr>

      </xsl:for-each>
    </table>
  </body>
  </html>
</xsl:template>
</xsl:stylesheet>
</code>```

here is my XML

```<code><?xml version="1.0" encoding="ISO-8859-1"?>
<NewDataSet>
  <AgentSales>
    <AgentName>MCCALLISTER AARON</AgentName>
    <State>Talking Out</State>
    <Reason />
    <time>9</time>
  </AgentSales>
  <AgentSales>
    <AgentName>APPELHANS BARRY</AgentName>
    <State>Talking Out</State>
    <Reason />
    <time>1</time>
  </AgentSales>
  <AgentSales>
    <AgentName>ARREDONDO KARLA</AgentName>
    <State>Talking Out</State>
    <Reason />
    <time>0</time>
  </AgentSales>
  <AgentSales>
    <AgentName>WOOTERS CHAD</AgentName>
    <State>Talking In</State>
    <Reason />
    <time>5</time>
  </AgentSales>
  <AgentSales>
    <AgentName>LANDINI EUGENE</AgentName>
    <State>Not Ready</State>
    <Reason>TRAINING</Reason>
    <time>16</time>
  </AgentSales>
  <AgentSales>
    <AgentName>BROWN EYES JONETTE</AgentName>
    <State>Not Ready</State>
    <Reason>TRAINING</Reason>
    <time>13</time>
  </AgentSales>
</NewDataSet>
</code>```

答:
While "apply-templates" may seem uncomfortable compared to "for-each", perhaps this example can show you its power...</p>

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
        <html>
            <body>
                <table cellpadding="3" cellspacing="0" width="390">
                    <tr>
                        <th style="text-align:left;"><span style="font:20px arial; font-weight:bold;">Agent Name</span></th>
                        <th style="text-align:center;"><span style="font:20px arial; font-weight:bold;">State</span></th>
                        <th style="text-align:center;"><span style="font:20px arial; font-weight:bold;">Time</span></th>
                    </tr>
                    <xsl:apply-templates select="NewDataSet/AgentSales[State!='Talking Out']"/>
                </table>
            </body>
        </html>
    </xsl:template>
    <xsl:template match="AgentSales">
        <tr>
            <xsl:if test="(position() mod 2 = 1)">
                <xsl:attribute name="bgcolor">#cccccc</xsl:attribute>
            </xsl:if>
            <td style="text-align:left;"><span style="font:14px arial; font-weight:bold;"><xsl:value-of select="AgentName"/></span></td>
            <td style="text-align:center;"><span style="font:14px arial; font-weight:bold;"><xsl:value-of select="State"/></span></td>
            <td style="text-align:center;"><span style="font:14px arial; font-weight:bold;"><xsl:value-of select="time"/></span></td>
        </tr>
    </xsl:template>
</xsl:stylesheet>
</code>```

Body:
Still having a hard time grasping some of the harder templates any help would be great.

Right now I am using a simple for-each loop that sorts and shows the data in a table. I want to do the same thing but skip over all the nodes where "State" is = to "Talking Out" below is my current style sheet and below that is my XML. I was thinking I could add a for-each inside of the current loop that ignores the nodes that meet my criteria. I am escaping single quotes since it is part of a larger php script.

<?xml version="1.0" encoding="ISO-8859-1"?>

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">

        Agent Name
        State
        Time

      <xsl:for-each select="NewDataSet/AgentSales">

 <xsl:if test="(position() mod 2 = 1)">
    <xsl:attribute name="bgcolor">#cccccc</xsl:attribute>
    </xsl:if>

 <xsl:if test="AgentSales[State=\'Talking Out\']">

    </xsl:if>

        <xsl:value-of select="AgentName"/>
        <xsl:value-of select="State"/>
    <xsl:value-of select="time"/>

      </xsl:for-each>

</xsl:template>
</xsl:stylesheet>

here is my XML

<?xml version="1.0" encoding="ISO-8859-1"?>
<NewDataSet>
  <AgentSales>
    <AgentName>MCCALLISTER AARON</AgentName>
    <State>Talking Out</State>
    <Reason />
    <time>9</time>
  </AgentSales>
  <AgentSales>
    <AgentName>APPELHANS BARRY</AgentName>
    <State>Talking Out</State>
    <Reason />
    <time>1</time>
  </AgentSales>
  <AgentSales>
    <AgentName>ARREDONDO KARLA</AgentName>
    <State>Talking Out</State>
    <Reason />
    <time>0</time>
  </AgentSales>
  <AgentSales>
    <AgentName>WOOTERS CHAD</AgentName>
    <State>Talking In</State>
    <Reason />
    <time>5</time>
  </AgentSales>
  <AgentSales>
    <AgentName>LANDINI EUGENE</AgentName>
    <State>Not Ready</State>
    <Reason>TRAINING</Reason>
    <time>16</time>
  </AgentSales>
  <AgentSales>
    <AgentName>BROWN EYES JONETTE</AgentName>
    <State>Not Ready</State>
    <Reason>TRAINING</Reason>
    <time>13</time>
  </AgentSales>
</NewDataSet>

Body:
While "apply-templates" may seem uncomfortable compared to "for-each", perhaps this example can show you its power...

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
        <html>
            <body>
                <table cellpadding="3" cellspacing="0" width="390">
                    <tr>
                        <th style="text-align:left;"><span style="font:20px arial; font-weight:bold;">Agent Name</span></th>
                        <th style="text-align:center;"><span style="font:20px arial; font-weight:bold;">State</span></th>
                        <th style="text-align:center;"><span style="font:20px arial; font-weight:bold;">Time</span></th>
                    </tr>
                    <xsl:apply-templates select="NewDataSet/AgentSales[State!='Talking Out']"/>
                </table>
            </body>
        </html>
    </xsl:template>
    <xsl:template match="AgentSales">
        <tr>
            <xsl:if test="(position() mod 2 = 1)">
                <xsl:attribute name="bgcolor">#cccccc</xsl:attribute>
            </xsl:if>
            <td style="text-align:left;"><span style="font:14px arial; font-weight:bold;"><xsl:value-of select="AgentName"/></span></td>
            <td style="text-align:center;"><span style="font:14px arial; font-weight:bold;"><xsl:value-of select="State"/></span></td>
            <td style="text-align:center;"><span style="font:14px arial; font-weight:bold;"><xsl:value-of select="time"/></span></td>
        </tr>
    </xsl:template>
</xsl:stylesheet>