问:
Access to external value inside apply
Short example:

```<code>class MyClass {
 val someName = "want this value"
 val someOther = SomeOther().apply{ someName = someName }
 // other stuff below
}
</code>```

SomeOther will apply the value of its own someName to someName, so value application makes no difference (x=x).

Q: How can I access external someName ("want this value") being inside apply?

UPDATE
I have further doubts related to suggestion to use this.someName=someName, below 2 code snippets, the first one works as expected, surprisingly the second fails with similar behavior as described.

First

```<code>fun main(args: Array<String>) {
    class SomeOther {
        var someName: String? = null
    }
    val someName = "want this value"
    print(SomeOther().apply { this.someName = someName }.someName) // works!

}
</code>```

Second

```<code>class SomeOther {
    var someName: String? = null
}

class MyClass {
    val someName = "want this value"
    val someOther = SomeOther().apply { this.someName = someName }
    fun go() = print(someOther.someName)
}

fun main(args: Array<String>) = MyClass().go() // prints null
</code>```

Q: Where's the difference?

答:
You could use the also-function instead. It is equivalent to apply, except it will bind your object to it instead of this:

```<code>val someName = "want this value"
val someOther = SomeOther().also { it.someName = someName }
</code>```

The also-function was added to Kotlin 1.1 specifially for when you do not want to shadow this from the outer scope.

Title: Access to external value inside apply

Body:
Short example:

class MyClass {
 val someName = "want this value"
 val someOther = SomeOther().apply{ someName = someName }
 // other stuff below
}

SomeOther will apply the value of its own someName to someName, so value application makes no difference (x=x).

Q: How can I access external someName ("want this value") being inside apply?

UPDATE
I have further doubts related to suggestion to use this.someName=someName, below 2 code snippets, the first one works as expected, surprisingly the second fails with similar behavior as described.

First

fun main(args: Array<String>) {
    class SomeOther {
        var someName: String? = null
    }
    val someName = "want this value"
    print(SomeOther().apply { this.someName = someName }.someName) // works!

}

Second

class SomeOther {
    var someName: String? = null
}

class MyClass {
    val someName = "want this value"
    val someOther = SomeOther().apply { this.someName = someName }
    fun go() = print(someOther.someName)
}

fun main(args: Array<String>) = MyClass().go() // prints null

Q: Where's the difference?

Body:
You could use the also-function instead. It is equivalent to apply, except it will bind your object to it instead of this:

val someName = "want this value"
val someOther = SomeOther().also { it.someName = someName }

The also-function was added to Kotlin 1.1 specifially for when you do not want to shadow this from the outer scope.


来源: stackexchange

问:
flex and data concurrency
I am soon to embark on a medium scale project. Although this isn't a very high priority in my large list of things to do but I have been trying of how I could affectively handle data concurrency.
I will be using a stateless EJB backend to my flex application.

Ideally I am looking for a simple method to deal with data concurrency. e.g. if data is saved on one interface it is refreshed in another. Or it warns that the data has been changed before saving a new version of the data.

Has anyone any ideas as I am at a loss at the moment. As I mentioned its not a high priority but I would feel a lot better if I had some mechanism to improve the process.

答:
Version control systems store user_id and datetime for every revision. You can use same method. Client app get current datetime for requested data and save it. App send on changed data with saved datetime. Server checks datetime of last revision and received datetime. And reply to app accordingly.

Second method is using broadcast messages from server to clients. But I don't think it's applicable in your case. This method put into practice in LAN (environment with stable connect) usually.

ContentLicense: CC BY-SA 3.0

Title: flex and data concurrency

ContentLicense: CC BY-SA 2.5


问:
SQL Server: Calculate amortization
Currently i'm struggling to solve following problem:

I have two tables (contract & amortization).

Contract:     contract informations with an outstanding amount

Amortization: date of payment & amortization amount

My desired result is a table with the contract and the decreasing
oustanding amount.

```<code>;WITH CTE AS
(
        SELECT con.ID
              ,con.outstanding
              ,amo.amortization
              ,amo.amo_date
              ,ROW_NUMBER() OVER ( PARTITION BY con.ID
                                       ORDER BY amo.amo_date asc
                                  ) as rn
          FROM contract con
    INNER JOIN amort amo
            ON amo.contractID = con.ID
)
SELECT ID
      ,outstanding
      ,outstanding - amortization as new_outstanding
      ,amo_date
  FROM CTE
</code>```

Currently i am getting this result - which is of course wrong, as just one amortization is calculated for the new_outstanding:

```<code>ID  outstanding     new_outstanding     amo_date
1   100000          90000               01.08.2017 00:00:00
1   100000          80000               01.09.2017 00:00:00
1   100000          50000               01.10.2017 00:00:00
1   100000          90000               01.11.2017 00:00:00
1   100000          90000               01.12.2017 00:00:00
</code>```

My desired result would be:

```<code>ID  outstanding     new_outstanding     amo_date
1   100000          90000               01.08.2017 00:00:00
1   100000          70000               01.09.2017 00:00:00
1   100000          20000               01.10.2017 00:00:00
1   100000          10000               01.11.2017 00:00:00
1   100000          0                   01.12.2017 00:00:00
</code>```

Any simple idea to solve this in an easy way?

Rextester: http://rextester.com/SBLT77863

Thanks in advance!

答:
I think you just need a cumulative sum:</p>

```<code>SELECT con.ID,
       con.outstanding,
       amo.amortization,
       amo.amo_date,
       (con.outstanding -
        sum(amo.amortization) over (partition by amo.contractId
                                    order by amo.amo_date)
       ) as new_outstanding
FROM contract con INNER JOIN
     amort amo
     ON amo.contractID = con.ID;
</code>```

Title: SQL Server: Calculate amortization

Body:
Currently i'm struggling to solve following problem:

I have two tables (contract & amortization).

Contract:     contract informations with an outstanding amount

Amortization: date of payment & amortization amount

My desired result is a table with the contract and the decreasing
oustanding amount.

;WITH CTE AS
(
        SELECT con.ID
              ,con.outstanding
              ,amo.amortization
              ,amo.amo_date
              ,ROW_NUMBER() OVER ( PARTITION BY con.ID
                                       ORDER BY amo.amo_date asc
                                  ) as rn
          FROM contract con
    INNER JOIN amort amo
            ON amo.contractID = con.ID
)
SELECT ID
      ,outstanding
      ,outstanding - amortization as new_outstanding
      ,amo_date
  FROM CTE

Currently i am getting this result - which is of course wrong, as just one amortization is calculated for the new_outstanding:

ID  outstanding     new_outstanding     amo_date
1   100000          90000               01.08.2017 00:00:00
1   100000          80000               01.09.2017 00:00:00
1   100000          50000               01.10.2017 00:00:00
1   100000          90000               01.11.2017 00:00:00
1   100000          90000               01.12.2017 00:00:00

My desired result would be:

ID  outstanding     new_outstanding     amo_date
1   100000          90000               01.08.2017 00:00:00
1   100000          70000               01.09.2017 00:00:00
1   100000          20000               01.10.2017 00:00:00
1   100000          10000               01.11.2017 00:00:00
1   100000          0                   01.12.2017 00:00:00

Any simple idea to solve this in an easy way?

Rextester: http://rextester.com/SBLT77863

Thanks in advance!

Body:
I think you just need a cumulative sum:

SELECT con.ID,
       con.outstanding,
       amo.amortization,
       amo.amo_date,
       (con.outstanding -
        sum(amo.amortization) over (partition by amo.contractId
                                    order by amo.amo_date)
       ) as new_outstanding
FROM contract con INNER JOIN
     amort amo
     ON amo.contractID = con.ID;


问:
How to setup "master" in a sub folder
In a Git repository, I need to change the path of the "master" branch to a subfolder instead of the root folder (default).

Example:

```<code>/ -> contains some config files, could be the "sources" branch

/master/ -> contains the files of the "master" branch
</code>```

Is this possible? How can I do it?

More precisions:

Usually I use Github pages feature, so I use the "worktree" feature to set the "gh-pages" branch in a subfolder. With Hugo, this is in "/public". See Hugo's documentation for details:

https://gohugo.io/tutorials/github-pages-blog/

Git's worktree feature:

https://git-scm.com/docs/git-worktree

However, on one of the server, generated files must be in /, in "master". So if I still want to have Hugo source files in the same repositories, I need to have them in an other folder and/or branch.

答:
A Git branch is a pointer to a commit. A Git commit contains the status of the entire project at some moment in time. At most one branch can be active and it brings all the project to the state of the project when the commit it points to was created.

It is possible to checkout the config files from the "sources" branch while the "master" branch is the current branch but this only changes the content of the checked out files in the working tree. Those files will probably be reported as "Changed" by git status; the changes will, however, be committed to the current branch ("master").

It is not possible to get what you described in the question.

Or, maybe, the question doesn't express correctly what you need.

Title: How to setup "master" in a sub folder

Body:
In a Git repository, I need to change the path of the "master" branch to a subfolder instead of the root folder (default).

Example:

/ -> contains some config files, could be the "sources" branch

/master/ -> contains the files of the "master" branch

Is this possible? How can I do it?

More precisions:

Usually I use Github pages feature, so I use the "worktree" feature to set the "gh-pages" branch in a subfolder. With Hugo, this is in "/public". See Hugo's documentation for details:

https://gohugo.io/tutorials/github-pages-blog/

Git's worktree feature:

https://git-scm.com/docs/git-worktree

However, on one of the server, generated files must be in /, in "master". So if I still want to have Hugo source files in the same repositories, I need to have them in an other folder and/or branch.


问:
undesired polyline rendering while zooming in and out google maps
rendering reflected image of the polyline

I have an application to draw a polyline on latitude and longitude values which are fetched dynamically. I'm able to form the polyline perfectly but I see a reflected polyline forming somewhere around the map as I extend the polyline asynchronously which is undesirable (i get this issue even if I don't change the zoom of the map). please help me avoid that reflection

答:
This is likely a Chrome browser issue.

The corresponding bug in the public issue tracker is

https://issuetracker.google.com/issues/38211242

Feel free to star the bug to add your vote and subscribe to further updates.

UPDATE

As stated in Google issue tracker, the issue was fixed in Chrome 60. The corresponding bug was marked as Fixed on August 9, 2017.


问:
CSS3 :target on named tag not working
I am having a hard time getting :target to work on a named tag.

The fiddle is here: https://jsfiddle.net/vgcLartp/1

Any ideas why this is not working?

答:
You need to use target on the sections that you want to show not the links

```<code>section:target {...}
</code>```

See updated jsfiddle

nav {
  height: 60px;
  border-bottom: 1px solid #eaeaea;
}

.nav-item {
  display: block;
  float: left;
  margin-right: 20px;
  height: 60px;
  font-size: 26px;
  line-height: 60px;
  text-align: center;
  overflow: hidden;
  color: #666;
  text-decoration: none;
  border-bottom: 3px solid transparent;
  outline: none;
}

.nav-item:last-child {
  margin-right: 0;
}

.nav-item:hover {
  color: #333;
}

.nav-item.active,
.nav-item.active:hover {
  color: #333;
  border-bottom-color: #b39095;
}

section:target {
  visibility: visible;
  opacity: 1;
}

/* -------------------------------- SECTIONS -------------------------------- */

#sections {
  float: left;
  width: 1200px;
  height: 400px;
}

section {
  position: fixed;
  width: 630px;
  height: 400px;
  float: left;
  opacity: 0;
  visibility: hidden;
  transition: opacity 0.5s linear;
}

section p {
  padding-top: 5px;
  line-height: 1.6em;
}

section a {
  color: #b39095;
  text-decoration: none;
}

section a:hover {
  color: #7b618a;
}

/* --------------------------------- OPTIONS -------------------------------- */

fieldset {
  margin: 26px 0 15px 0;
  border: 1px solid #ccc;
  border-radius: 3px;
  padding: 10px;
}

input {
  padding-left: 2px;
}

#oxford-app-id {
  width: 80px;
}

#oxford-app-key {
  width: 290px;
}

label {
  padding-left: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <header>
    <nav>
      options<br>saved
      about
    </nav>
  </header>

  <div id="sections">
    <section id="section-options">
      <p>
        Options
      </p>
    </section>
    <section id="section-about">
      <p>
        About
      </p>
    </section>
  </div>

</div></code>```

Title: CSS3 :target on named tag not working

Body:
You need to use target on the sections that you want to show not the links

section:target {...}

See updated jsfiddle

nav {
  height: 60px;
  border-bottom: 1px solid #eaeaea;
}

.nav-item {
  display: block;
  float: left;
  margin-right: 20px;
  height: 60px;
  font-size: 26px;
  line-height: 60px;
  text-align: center;
  overflow: hidden;
  color: #666;
  text-decoration: none;
  border-bottom: 3px solid transparent;
  outline: none;
}

.nav-item:last-child {
  margin-right: 0;
}

.nav-item:hover {
  color: #333;
}

.nav-item.active,
.nav-item.active:hover {
  color: #333;
  border-bottom-color: #b39095;
}

section:target {
  visibility: visible;
  opacity: 1;
}

/* -------------------------------- SECTIONS -------------------------------- */

#sections {
  float: left;
  width: 1200px;
  height: 400px;
}

section {
  position: fixed;
  width: 630px;
  height: 400px;
  float: left;
  opacity: 0;
  visibility: hidden;
  transition: opacity 0.5s linear;
}

section p {
  padding-top: 5px;
  line-height: 1.6em;
}

section a {
  color: #b39095;
  text-decoration: none;
}

section a:hover {
  color: #7b618a;
}

/* --------------------------------- OPTIONS -------------------------------- */

fieldset {
  margin: 26px 0 15px 0;
  border: 1px solid #ccc;
  border-radius: 3px;
  padding: 10px;
}

input {
  padding-left: 2px;
}

#oxford-app-id {
  width: 80px;
}

#oxford-app-key {
  width: 290px;
}

label {
  padding-left: 5px;
}

<div id="container">
  <header>
    <nav>
      <a id="options" class="nav-item active" href="#section-options">options<br>saved</a>
      <a id="about" class="nav-item" href="#section-about">about</a>
    </nav>
  </header>

  <div id="sections">
    <section id="section-options">
      <p>
        Options
      </p>
    </section>
    <section id="section-about">
      <p>
        About
      </p>
    </section>
  </div>

</div>


问:
Unable to display array content
```<code>        var dataHolder = [
        {
            "letterA" : "Fruits",
            "letterB" : "Veges",
            "letterC" : "Meat"
        }
    ];
    console.log(dataHolder[0].letterA);
    var result = "";
    function getData(myLetter) {
        for (var i = 0; i < dataHolder.length; i++) {
           if(dataHolder[i][myLetter] === myLetter){
               console.log(dataHolder[i][myLetter]);
           }
           else{
               console.log("No data found");
           }
            }
        }
    getData("letterA");
</code>```

This is my code and i'm just trying to match the content of the array with the passed parameter, but every time it's giving No data found as output and not the matching content, it seems i'm missing something very basic here.
Any help would be highly appreciated.Thanks!!

答:
You are comparing value with key that is wrong.

The hasOwnProperty() method returns a boolean indicating whether the
  object has the specified property as own (not inherited) property.

Use hasOwnProperty to check key exists or not.

```<code>dataHolder[i].hasOwnProperty(myLetter)
</code>```

var dataHolder = [
        {
            "letterA" : "Fruits",
            "letterB" : "Veges",
            "letterC" : "Meat"
        }
    ];

    var result = "";
    function getData(myLetter) {
        for (var i = 0; i < dataHolder.length; i++) {

           if(dataHolder[i].hasOwnProperty(myLetter)){
               console.log(dataHolder[i][myLetter]);
           }
           else{
               console.log("No data found");
           }
            }
        }
    getData("letterA");```

Title: Unable to display array content

Body:
        var dataHolder = [
        {
            "letterA" : "Fruits",
            "letterB" : "Veges",
            "letterC" : "Meat"
        }
    ];
    console.log(dataHolder[0].letterA);
    var result = "";
    function getData(myLetter) {
        for (var i = 0; i < dataHolder.length; i++) {
           if(dataHolder[i][myLetter] === myLetter){
               console.log(dataHolder[i][myLetter]);
           }
           else{
               console.log("No data found");
           }
            }
        }
    getData("letterA");

This is my code and i'm just trying to match the content of the array with the passed parameter, but every time it's giving No data found as output and not the matching content, it seems i'm missing something very basic here.
Any help would be highly appreciated.Thanks!!

Body:
You are comparing value with key that is wrong.

The hasOwnProperty() method returns a boolean indicating whether the
  object has the specified property as own (not inherited) property.

Use hasOwnProperty to check key exists or not.

dataHolder[i].hasOwnProperty(myLetter)

var dataHolder = [
        {
            "letterA" : "Fruits",
            "letterB" : "Veges",
            "letterC" : "Meat"
        }
    ];

    var result = "";
    function getData(myLetter) {
        for (var i = 0; i < dataHolder.length; i++) {

           if(dataHolder[i].hasOwnProperty(myLetter)){
               console.log(dataHolder[i][myLetter]);
           }
           else{
               console.log("No data found");
           }
            }
        }
    getData("letterA");


问:
Using schema Auto-Detection in BigQuery and c#
Goal:

Uploading a .csv file to Google BigQuery by using the Google.Cloud.BigQuery.V2 -Pre c# package with auto creating a table if it doesnt exists.

Problem:

It's possible to auto-detect the database scheme and create a new table if it doesnt exist. This option is enabled by default. However, if I try to upload an .csv to a not-existing table, a new table is not created. It shows me an errormsg.

I think it might be something with the TableSchema since I don't know how to create a TableSchema based on the .csv file.

```<code>Google.GoogleApiException: 'Google.Apis.Requests.RequestError

Not found: Table project-id-here:dataset-id-here.table-id-here [404]

Errors [
Message[Not found: Table project-id-here:dataset-id-here.table-id-here] Location[ - ] Reason[notFound] Domain[global]
]
</code>```

Code:

```<code>    string fileName = @"C:\result.csv";
    string projectId = "project-id-here";
    string datasetId = "dataset-id-here";
    string tableId = "table-id-here";

    BigQueryClient client = BigQueryClient.Create(projectId);
    TableSchema schema = null;

    using (FileStream stream = File.Open(fileName, FileMode.Open))
    {

        Console.WriteLine("Starting polling...");
        // This example uploads data to an existing table. If the upload will create a new table
        // or if the schema in the JSON isn't identical to the schema in the table,
        // create a schema to pass into the call instead of passing in a null value.
         BigQueryJob job = client.UploadCsv(datasetId, tableId, schema, stream, new UploadCsvOptions { SkipLeadingRows = 10 });

        // Use the job to find out when the data has finished being inserted into the table,
        // report errors etc.

        BigQueryJob result = job.PollUntilCompleted();
        // If there are any errors, display them *then* fail.
        if (result.Status.ErrorResult != null)
        {
            foreach (ErrorProto error in result.Status.Errors)
            {
                Console.WriteLine(error.Message);
            }
        }

        Console.WriteLine("Polling ended");

    }
</code>```

Thanks in advance. :)

答:
This functionality has been added in release 1.0.0-beta13. Auto-schema is needed to create the table OR you'd have to specify this by hand. The dataset has to be there, it wasnt there when I tried to upload my data.

https://github.com/GoogleCloudPlatform/google-cloud-dotnet/issues/1166

Body:
Goal:

Uploading a .csv file to Google BigQuery by using the Google.Cloud.BigQuery.V2 -Pre c# package with auto creating a table if it doesnt exists.

Problem:

It's possible to auto-detect the database scheme and create a new table if it doesnt exist. This option is enabled by default. However, if I try to upload an .csv to a not-existing table, a new table is not created. It shows me an errormsg.

I think it might be something with the TableSchema since I don't know how to create a TableSchema based on the .csv file.

Google.GoogleApiException: 'Google.Apis.Requests.RequestError

Not found: Table project-id-here:dataset-id-here.table-id-here [404]

Errors [
Message[Not found: Table project-id-here:dataset-id-here.table-id-here] Location[ - ] Reason[notFound] Domain[global]
]

Code:

    string fileName = @"C:\result.csv";
    string projectId = "project-id-here";
    string datasetId = "dataset-id-here";
    string tableId = "table-id-here";

    BigQueryClient client = BigQueryClient.Create(projectId);
    TableSchema schema = null;

    using (FileStream stream = File.Open(fileName, FileMode.Open))
    {

        Console.WriteLine("Starting polling...");
        // This example uploads data to an existing table. If the upload will create a new table
        // or if the schema in the JSON isn't identical to the schema in the table,
        // create a schema to pass into the call instead of passing in a null value.
         BigQueryJob job = client.UploadCsv(datasetId, tableId, schema, stream, new UploadCsvOptions { SkipLeadingRows = 10 });

        // Use the job to find out when the data has finished being inserted into the table,
        // report errors etc.

        BigQueryJob result = job.PollUntilCompleted();
        // If there are any errors, display them *then* fail.
        if (result.Status.ErrorResult != null)
        {
            foreach (ErrorProto error in result.Status.Errors)
            {
                Console.WriteLine(error.Message);
            }
        }

        Console.WriteLine("Polling ended");

    }

Thanks in advance. :)


问:
Play Video immediately when UIView is loaded
Howdy! I'm writing an iPad app, and I need to be able to play a video when a UIView loads. However, I was getting a BAD_EXC_ACCESS if I try to message my MPMoviePlayerController anywhere after I initialize it. I removed the MPMediaPlayerController from my *.h file, then declared it entirely in the implementation file, and now I'm getting the message at the bottom below my code. There are no issues in Build and Analyze about memory leaks (or any issues, for that matter), and I cannot find any posts about this. Here's my code:

```<code>    - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {

    }

 NSString *url = [[NSBundle mainBundle] pathForResource:@"p0600c0100cmpintro" ofType:@"m4v"];
 MPMoviePlayerController *movie = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL fileURLWithPath:url]];
 NSLog(@"%@", movie);
 movie.view.frame = CGRectMake(5, 0, 1035, 768);
 movie.view.contentMode = UIViewContentModeScaleToFill;
 [[movie view] setCenter:CGPointMake(movie.view.center.x-10, movie.view.center.y)];
 [movie setControlStyle:MPMovieControlStyleNone];
    [movie setShouldAutoplay:YES];
 [[self view] addSubview:[movie view]];

    return self;
    }
</code>```

The NSLog of "movie" gives "MPMoviePlayerController: 0x1b77f0", but then the error message upon crash is "* -[MPMoviePlayerController playbackState]: message sent to deallocated instance 0x1473a0". Help?

答: I would suggest creating your MoviePlayer in viewDidLoad, then in viewDidAppear make the movie play, for best results.

Body:
Howdy! I'm writing an iPad app, and I need to be able to play a video when a UIView loads. However, I was getting a BAD_EXC_ACCESS if I try to message my MPMoviePlayerController anywhere after I initialize it. I removed the MPMediaPlayerController from my *.h file, then declared it entirely in the implementation file, and now I'm getting the message at the bottom below my code. There are no issues in Build and Analyze about memory leaks (or any issues, for that matter), and I cannot find any posts about this. Here's my code:

    - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {

    }

 NSString *url = [[NSBundle mainBundle] pathForResource:@"p0600c0100cmpintro" ofType:@"m4v"];
 MPMoviePlayerController *movie = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL fileURLWithPath:url]];
 NSLog(@"%@", movie);
 movie.view.frame = CGRectMake(5, 0, 1035, 768);
 movie.view.contentMode = UIViewContentModeScaleToFill;
 [[movie view] setCenter:CGPointMake(movie.view.center.x-10, movie.view.center.y)];
 [movie setControlStyle:MPMovieControlStyleNone];
    [movie setShouldAutoplay:YES];
 [[self view] addSubview:[movie view]];

    return self;
    }

The NSLog of "movie" gives "MPMoviePlayerController: 0x1b77f0", but then the error message upon crash is "* -[MPMoviePlayerController playbackState]: message sent to deallocated instance 0x1473a0". Help?


问:
JMeter can I run it locally?
In my opinion, load tests should be performed from several different IP addresses simultaneously(because of restrictions on http). Am I right?

I will do load tests for:
Number of Threads (users):  2000
Ramp-Up Period (in seconds): 10

答:
The load doesn't necessarily have to come from different IP addresses however depending on your application nature it might be required (for example application does explicit check of origin IP address or lives behind a load balancer with session stickiness based on IP addresses or whatever)

In this case you can perform IP spoofing so each request would come from the different IP address, you can configure source IP address under "Source address" input on the "Advanced" tab of the HTTP Request sampler

See Using IP Spoofing to Simulate Requests from Different IP Addresses with JMeter for more details.

Title: JMeter can I run it locally?


问:
How to implement PReLU activation in Tensorflow?
The Parametric Rectified Linear Unit (PReLU) is an interesting and widely used activation function. It seems that Tensorflow (reference link) does not provide PReLU. I know that the higher level libraries, such as Keras and TFLearn, has the implementation of it.

I would like to know how to implement PReLU in Tensorflow?

答:
Although the solution with tf.maximum is very efficient, it can't represent a concave function. Here's a solution that can:

def prelu(_x, scope=None):
    """parametric ReLU activation"""
    with tf.variable_scope(name_or_scope=scope, default_name="prelu"):
        _alpha = tf.get_variable("prelu", shape=_x.get_shape()[-1],
                                 dtype=_x.dtype, initializer=tf.constant_initializer(0.1))
        return tf.maximum(0.0, _x) + _alpha * tf.minimum(0.0, _x)
```


问:
Loopback - Setting Up environment specific configuration
Hi can I get some help with setting environment specific configuration.
I have two files for datasource

server/datasources.json

server/datasources.test.json

I use the script "SET NODE_ENV=test && mocha test/**/*.test.js" on WIndows to run my test cases and set the node environment to test.
Loopback does not load server/datasource.test.json instead the datasource from server/datasource.json is loaded.

I have confirmend the environment using process.env.NODE_ENV which logs "test

I have tried to change server/datasource.json to server/datasource.local.json, But then I get an error
WARNING: Main config file "datasources.json" is missing.

I dont understand what I am doing wrong.Am I supposed to create all the config files for the test environment like *.test.json.
Or is there a different config file where I have to define envrionment specific files.

Please check this repo https://github.com/dhruv004/sample-loopback-example
From the code If you run npm run test It loads data from local.json which is the data source for development environment.It should load data from test.json(datasource for test environment)

答:
Looking on your repository, I can see this note from LoopBack documentation particulary relevant for you:

A LoopBack application can load multiple configuration files, that can potentially conflict with each other. The value set by the file with the highest priority will always take effect. The priorities are:

Environment-specific configuration, based on the value of NODE_ENV; for example, server/config.staging.json.

Local configuration file; for example, server/config.local.json.

Default configuration file; for example, server/config.json.

In your model-config.json all models have datasource set to db so in your case LoopBack application loads first datasources.test.json. It cannot find datasource db there (only testdb), so it falls back to datasources.json. There it finds datasource db and it uses it. Try renaming testdb in datasources.test.json to db and it will take a precedense.


问:
how to remove carriage return in js
I have set of numbers from an excel like this
05143
05250
05252
05156
05143
05441
05143
05031
05050
05101
05821
05822
05861

and after every 5th digit I wanted to add a ,
My problem is that after every 5th digit it considers a white space carriage as a digit and then split the items such as

05143 ↵0525 0↵052 50↵05 and so on...

and that's why , split is breaking. I tried to replace it  as item.replace(/↵/g, ""); but its not working.

here is my code

```<code>item.replace(/↵/g, "")
                console.log(item)
              if(item.length > 5){
                for (var i = 0; i < item.length; i += 5) {
                       chunks.push(item.substring(i, i + 5));
                   }
                   console.log(chunks)
                    var tempItem;
                     chunks.forEach(function(item2) {
                       if (tempItem == undefined) {
                         tempItem = "'" + item2 + "'";
                       } else {
                         tempItem = tempItem + ",'" + item2 + "'";
                       }
                     })
</code>```

答:
it works when we write it as </p>

```<code>item.split('\n')
</code>```

Title: how to remove carriage return in js

Body:
I have set of numbers from an excel like this
05143
05250
05252
05156
05143
05441
05143
05031
05050
05101
05821
05822
05861

and after every 5th digit I wanted to add a ,
My problem is that after every 5th digit it considers a white space carriage as a digit and then split the items such as

05143 ↵0525 0↵052 50↵05 and so on...

and that's why , split is breaking. I tried to replace it  as item.replace(/↵/g, ""); but its not working.

here is my code

item.replace(/↵/g, "")
                console.log(item)
              if(item.length > 5){
                for (var i = 0; i < item.length; i += 5) {
                       chunks.push(item.substring(i, i + 5));
                   }
                   console.log(chunks)
                    var tempItem;
                     chunks.forEach(function(item2) {
                       if (tempItem == undefined) {
                         tempItem = "'" + item2 + "'";
                       } else {
                         tempItem = tempItem + ",'" + item2 + "'";
                       }
                     })

Body:
it works when we write it as

item.split('\n')


问:
ASCII code not working in firefox but on chrome working fine
I had created function which allows to enter all characters and almost all symbols on chrome and that is working fine but on firefox I am not able to enter any character or any symbols

Below is my script

```<code>  function blockSpecialChar(e) {
    var k = e.keyCode;
    return ((k > 64 && k < 91) || (k > 96 && k < 123) || (k > 31 && k < 34) || (k > 34 && k < 38) || k == 8 || k == 64 || k == 95 || k == 61 || k == 63 || (k > 39 && k <= 57));
}
</code>```

.aspx code

```<code><asp:TextBox ID="txtdescribe"  onkeypress="return blockSpecialChar(event)" CssClass="input" ValidationGroup="services" runat="server" MaxLength="255"></asp:TextBox>
</code>```

This function restricts only html symbols to insert but on firefox it is not allowing to insert character also

Example on chrome

Example on firefox

答:
Try this:

```<code>function blockSpecialChar(e) {
        if (e == 60 || e == 62 || e == 34 || e == 38 || e == 39) {
            return false;
        }
        else {
            return true;
        }
}

onClick="ToggelDiv(this.id); Specialinstruction();"
</code>```

These will be work on all browsers.

Body:
I had created function which allows to enter all characters and almost all symbols on chrome and that is working fine but on firefox I am not able to enter any character or any symbols

Below is my script

  function blockSpecialChar(e) {
    var k = e.keyCode;
    return ((k > 64 && k < 91) || (k > 96 && k < 123) || (k > 31 && k < 34) || (k > 34 && k < 38) || k == 8 || k == 64 || k == 95 || k == 61 || k == 63 || (k > 39 && k <= 57));
}

.aspx code

<asp:TextBox ID="txtdescribe"  onkeypress="return blockSpecialChar(event)" CssClass="input" ValidationGroup="services" runat="server" MaxLength="255"></asp:TextBox>

This function restricts only html symbols to insert but on firefox it is not allowing to insert character also

Example on chrome

Example on firefox

Body:
Try this:

function blockSpecialChar(e) {
        if (e == 60 || e == 62 || e == 34 || e == 38 || e == 39) {
            return false;
        }
        else {
            return true;
        }
}

onClick="ToggelDiv(this.id); Specialinstruction();"

These will be work on all browsers.


问:
Template function specialization default
I'm trying to make a class which will work with specific data types and I want to have a compile-time error when data type is not supported.

I tried to specialize templates like this.

```<code>template<>
float Foo::get<float>(const std::string& key)
{
    return std::stof(key);
}
</code>```

And put a std::static_assert in the generic function because I only need these types that are specified.

```<code>template<class T>
T Foo::get(const std::string&)
{
    static_assert(false, "unsupported data type");
    return T(0);
}
</code>```

Unfortunately I get the compile error (static assert failed) even if I have a specialized function for this type.

I found a way to do it for the specific types only but it looks kinda stupid and its not generic.

```<code>T Foo::get(const std::string&)
{
    static_assert(
            std::is_same<T,float>::value ||
            std::is_same<T,double>::value ||
            std::is_same<T,bool>::value ||
            std::is_same<T,uint32_t>::value ||
            std::is_same<T,int32_t>::value ||
            std::is_same<T,std::string>::value,
            "unsuported data type");
    return T(0);
}
</code>```

答:
You may do

```<code>template <typename> struct AlwaysFalse : false_type {};

template<class T>
T Foo::get(const std::string&)
{
    static_assert(AlwaysFalse<T>::value, "unsupported data type");
}
</code>```

So the assert is template dependent.

Body:
I'm trying to make a class which will work with specific data types and I want to have a compile-time error when data type is not supported.

I tried to specialize templates like this.

template<>
float Foo::get<float>(const std::string& key)
{
    return std::stof(key);
}

And put a std::static_assert in the generic function because I only need these types that are specified.

template<class T>
T Foo::get(const std::string&)
{
    static_assert(false, "unsupported data type");
    return T(0);
}

Unfortunately I get the compile error (static assert failed) even if I have a specialized function for this type.

I found a way to do it for the specific types only but it looks kinda stupid and its not generic.

T Foo::get(const std::string&)
{
    static_assert(
            std::is_same<T,float>::value ||
            std::is_same<T,double>::value ||
            std::is_same<T,bool>::value ||
            std::is_same<T,uint32_t>::value ||
            std::is_same<T,int32_t>::value ||
            std::is_same<T,std::string>::value,
            "unsuported data type");
    return T(0);
}

Body:
You may do

template <typename> struct AlwaysFalse : false_type {};

template<class T>
T Foo::get(const std::string&)
{
    static_assert(AlwaysFalse<T>::value, "unsupported data type");
}

So the assert is template dependent.


问:
c# easiest way to extract substring
i have a string:

```<code>string somestring = "\\\\Tecan1\\tecan #1 output\\15939-E.ESY"
</code>```

i need to extract 15939

it will always be a 5 digit number, always preceeded by '\' and it will always "-" after it

答:
Try (based on your answer in the comments about the \ character):

```<code>string result = myString.SubString(myString.LastIndexOf(@"\") + 1, 5);
</code>```

Title: c# easiest way to extract substring

Body:
i have a string:

string somestring = "\\\\Tecan1\\tecan #1 output\\15939-E.ESY"

i need to extract 15939

it will always be a 5 digit number, always preceeded by '\' and it will always "-" after it

Body:
Try (based on your answer in the comments about the \ character):

string result = myString.SubString(myString.LastIndexOf(@"\") + 1, 5);


问:
Angular $http.get doesn't return what i expected
I'm trying to do a simple http get request but it doesn't return what i expected.

Here is the code

.js :

```<code>$http.get("database.php").success(function(data, status)
{
    alert(data);
    $scope.data = data;
}
).error(function(data, status)
{
    $scope.untruc = "Error";
});
</code>```

.php :

```<code><?php
header('Content-type: application/json');

$conn = // my connection

// Check connection
if ($conn->connect_error)
    echo "Connection failed";
else
{
    $sql = "SELECT id FROM user";
    $result = $conn->query($sql);
    echo json_encode($result);
}
</code>```

?>

and the ouput is :

```<code>data : <?php header('Content-type: application/json'); $conn = // my connection; // Check connection    if ($conn->connect_error) echo "Connection failed"; else { $sql = "SELECT id FROM user"; $result = $conn->query($sql); echo json_encode($result); } ?>
</code>```

literaly the code...

I'm expecting it to get the $result. Do you know how i could do that ?

答:
Please check you php code once.
And try to implement this code

<?php
header('Content-type: application/json');

$conn = new mysqli('localhost', 'root', 'password', 'database');

// Check connection
if ($conn->connect_error)
    echo "Connection failed";
else
{
    $sql = "SELECT * FROM users";
    $result = $conn->query($sql);
    $myresult = [];
    $i =0;
    while($row = $result->fetch_array()) {
  $myresult[$i] = $row;
  $i++;
 }

    //echo "```";
    echo json_encode($myresult);
}

?></code>```

Body:
I'm trying to do a simple http get request but it doesn't return what i expected.

Here is the code

.js :

$http.get("database.php").success(function(data, status)
{
    alert(data);
    $scope.data = data;
}
).error(function(data, status)
{
    $scope.untruc = "Error";
});

.php :

<?php
header('Content-type: application/json');

$conn = // my connection

// Check connection
if ($conn->connect_error)
    echo "Connection failed";
else
{
    $sql = "SELECT id FROM user";
    $result = $conn->query($sql);
    echo json_encode($result);
}

?>

and the ouput is :

data : <?php header('Content-type: application/json'); $conn = // my connection; // Check connection    if ($conn->connect_error) echo "Connection failed"; else { $sql = "SELECT id FROM user"; $result = $conn->query($sql); echo json_encode($result); } ?>

literaly the code...

I'm expecting it to get the $result. Do you know how i could do that ?

Body:
Please check you php code once.
And try to implement this code

<?php
header('Content-type: application/json');

$conn = new mysqli('localhost', 'root', 'password', 'database');

// Check connection
if ($conn->connect_error)
    echo "Connection failed";
else
{
    $sql = "SELECT * FROM users";
    $result = $conn->query($sql);
    $myresult = [];
    $i =0;
    while($row = $result->fetch_array()) {
  $myresult[$i] = $row;
  $i++;
 }

    //echo "<pre>";
    echo json_encode($myresult);
}

?>


问:
Json recognised as String
I am trying to read the response of the server that gives me the following JSON:

```<code>{"result": "Success", "message": "[{\"model\": \"mysite.userprofile\", \"pk\": 1}, {\"model\": \"mysite.userprofile\", \"pk\": 4}]"}
</code>```

When I try to read it I get as is a String. If I try to parse it is not possible as it gives me

Unexpected token o in JSON at position 1

which  means that is a Json already.

So this code:

```<code>$.ajax({
            type: 'POST',
            contentType: 'application/json',
            dataType: 'json',
            url: '/search/?city=&radius=',
            success: function (data) {
                //data = JSON.parse(data);
                var ul = document.getElementById("contact-list");
                console.log("JSON?  "+data.message[0]); // Print [ which is the first char

                for (var x = 0; x < data.message.length; x++){
                     // iterate throw every character in the message
                }
</code>```

So inside the properties ('result' and 'message') it appears as there is a String instead of a Json

And here is the server side:

```<code>def search_profiles_by_loc(request):
    if request.method == "POST" and request.is_ajax():
        city = request.POST.get('city', False)
        all_profiles = UserProfile.objects.all()
        response_data = {}
        response_data['result'] = 'Success'
        response_data['message'] = serializers.serialize('json', all_profiles)
        return HttpResponse(JsonResponse(response_data), content_type="application/json")
</code>```

I tried a lot of things nothing work

答:
As harish-reddy said, the dataType property sets the behaviour to what you expect the response to be. That said the "data" argument of the success function is already a JavaScript object.

Refer to http://api.jquery.com/jQuery.ajax/

As arpit-solanki mentioned the message property inside the response object is not an array, but is interpreted as a string (notice the starting '"'), therefor you either change the server side to send you an actual array or you must JSON.parse(data.message) to obtain its content.

Title: Json recognised as String

Body:
I am trying to read the response of the server that gives me the following JSON:

{"result": "Success", "message": "[{\"model\": \"mysite.userprofile\", \"pk\": 1}, {\"model\": \"mysite.userprofile\", \"pk\": 4}]"}

When I try to read it I get as is a String. If I try to parse it is not possible as it gives me

Unexpected token o in JSON at position 1

which  means that is a Json already.

So this code:

$.ajax({
            type: 'POST',
            contentType: 'application/json',
            dataType: 'json',
            url: '/search/?city=&radius=',
            success: function (data) {
                //data = JSON.parse(data);
                var ul = document.getElementById("contact-list");
                console.log("JSON?  "+data.message[0]); // Print [ which is the first char

                for (var x = 0; x < data.message.length; x++){
                     // iterate throw every character in the message
                }

So inside the properties ('result' and 'message') it appears as there is a String instead of a Json

And here is the server side:

def search_profiles_by_loc(request):
    if request.method == "POST" and request.is_ajax():
        city = request.POST.get('city', False)
        all_profiles = UserProfile.objects.all()
        response_data = {}
        response_data['result'] = 'Success'
        response_data['message'] = serializers.serialize('json', all_profiles)
        return HttpResponse(JsonResponse(response_data), content_type="application/json")

I tried a lot of things nothing work


答:
You can make static_assert depending on the template parameter T, then it won't be evaluated until the time of instantiation, i.e. the time the exact type is explored as template argument. e.g.

```<code>template<class T>
T get(const std::string&)
{
    static_assert(!std::is_same<T, T>::value, "unsupported data type");
    return T(0);
}
</code>```

LIVE

Title: Template function specialization default

Body:
You can make static_assert depending on the template parameter T, then it won't be evaluated until the time of instantiation, i.e. the time the exact type is explored as template argument. e.g.

template<class T>
T get(const std::string&)
{
    static_assert(!std::is_same<T, T>::value, "unsupported data type");
    return T(0);
}

LIVE


问:
Pentaho get variables from table input to use it in sql script
I'm trying to get variables from table input, table input return this data:

ID, name

ID, name

.., ...

ID, name

I want to use this data to get other data in a other table input:

select id, name, date, nightmare from table where id = ${ID} and name = ${name}

or better:

select id, name, date, nightmare from table where id in ${ID} and name in ${name}

Note:
 - ${..} -> variable
 - I can't do subquery, each query are in different dbms

Thanks

答:
What you're after aren't variables, which would need to be set before the transformation initialises and are always single values.

You're after parameters.

Your Table input1 returns several rows of data with fields id and name; you connect it to a new Table Input where you want to pass these values, for example, in the where clause:

select * from customers
where id = ? and name = ?

The question marks will be replaced by the values coming from the previous step.

You just need to fill in the name of the first step in the box "Insert data from Step" and check the "Execute for each row" box.

Now your query will run once for each row arriving at that step, and the values will be replaced.

Caveat:

each parameter is used only once;

and they will be passed in the order in which they arrive;

all incoming fields must be used in the query.

If you need to use the same parameter multiple times or use them in a different order you'll need to change the structure of your incoming data stream with a Select Values step.


问:
Which is the best way to compress json to store in a memory based store like redis or memcache?
Requirement :
Python objects with 2-3 levels of nesting containing basic datypes like integers,strings, lists, and dicts.
( no dates etc), needs to be stored as json in redis against a key.
What are the best methods available for compressing json as a string for low memory footprint.
The target objects are not very large, having 1000 small elements on average,
or about 15000 characters when converted to JSON.

eg.

```<code>>>> my_dict
{'details': {'1': {'age': 13, 'name': 'dhruv'}, '2': {'age': 15, 'name': 'Matt'}}, 'members': ['1', '2']}
>>> json.dumps(my_dict)
'{"details": {"1": {"age": 13, "name": "dhruv"}, "2": {"age": 15, "name": "Matt"}}, "members": ["1", "2"]}'
### SOME BASIC COMPACTION ###
>>> json.dumps(my_dict, separators=(',',':'))
'{"details":{"1":{"age":13,"name":"dhruv"},"2":{"age":15,"name":"Matt"}},"members":["1","2"]}'
</code>```

1/ Are there any other better ways to compress json to save memory in redis ( also ensuring light weight decoding afterwards ).

2/ How good a candidate would be msgpack [http://msgpack.org/] ?

3/ Shall I consider options like pickle as well ?

答:
If you want it to be fast, try lz4.
If you want it to compress better, go for lzma.

Are there any other better ways to compress json to save memory in
  redis(also ensuring light weight decoding afterwards)?

How good a candidate would be msgpack [http://msgpack.org/]?

Msgpack is relatively fast and has a smaller memory footprint. But ujson is generally faster for me.
You should compare them on your data, measure the compression and decompression rates and the compression ratio.

Shall I consider options like pickle as well?

Consider both pickle(cPickle in partucular) and marshal. They are fast. But remember that they are not secure or scalable and you pay for the speed with the added responsibility.

Body:
Requirement :
Python objects with 2-3 levels of nesting containing basic datypes like integers,strings, lists, and dicts.
( no dates etc), needs to be stored as json in redis against a key.
What are the best methods available for compressing json as a string for low memory footprint.
The target objects are not very large, having 1000 small elements on average,
or about 15000 characters when converted to JSON.

eg.

>>> my_dict
{'details': {'1': {'age': 13, 'name': 'dhruv'}, '2': {'age': 15, 'name': 'Matt'}}, 'members': ['1', '2']}
>>> json.dumps(my_dict)
'{"details": {"1": {"age": 13, "name": "dhruv"}, "2": {"age": 15, "name": "Matt"}}, "members": ["1", "2"]}'
### SOME BASIC COMPACTION ###
>>> json.dumps(my_dict, separators=(',',':'))
'{"details":{"1":{"age":13,"name":"dhruv"},"2":{"age":15,"name":"Matt"}},"members":["1","2"]}'

1/ Are there any other better ways to compress json to save memory in redis ( also ensuring light weight decoding afterwards ).

2/ How good a candidate would be msgpack [http://msgpack.org/] ?

3/ Shall I consider options like pickle as well ?


问:
Symfony & Doctrine : UnitOfWork undefined index after calling flush()
I have 3 entities :

Folder :

```<code><?php
namespace CMS\ExtranetBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Folder
 *
 * @ORM\Table(name="folder")
 * @ORM\HasLifecycleCallbacks
 * @ORM\Entity(repositoryClass="CMS\ExtranetBundle\Repository\FolderRepository")
 */
class Folder
{
    /**
     * @ORM\Id
     * @ORM\Column(name="id", type="guid")
     * @ORM\GeneratedValue(strategy="UUID")
     */
    public $id;
    // Used in NotificationListener
    public $beforeRemoveId;
    /**
     * @ORM\OneToMany(targetEntity="Document", mappedBy="folder", cascade={"persist", "remove"})
     */
    public $documents;
}
</code>```

Document :

```<code><?php
namespace CMS\ExtranetBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Document
 * @ORM\Entity(repositoryClass="CMS\ExtranetBundle\Repository\DocumentRepository")
 * @ORM\Table(name="document")
 * @ORM\HasLifecycleCallbacks
 */
class Document
{
    /**
     * @ORM\Id
     * @ORM\Column(name="id", type="guid")
     * @ORM\GeneratedValue(strategy="UUID")
     */
    public $id;
    /**
     * @ORM\ManyToOne(targetEntity="Folder", inversedBy="documents", cascade={"persist"})
     * @ORM\JoinColumn(name="folder_id", referencedColumnName="id", nullable=true)
     */
    public $folder;
}
</code>```

and Notification :

```<code><?php
namespace CMS\ExtranetBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Table(name="notification")
 * @ORM\Entity(repositoryClass="CMS\ExtranetBundle\Repository\NotificationRepository")
 * @ORM\HasLifecycleCallbacks
 */
class Notification
{
    /**
     * @ORM\Id
     * @ORM\Column(name="id", type="guid")
     * @ORM\GeneratedValue(strategy="UUID")
     */
    public $id;
    /**
     * @ORM\ManyToOne(targetEntity="User", inversedBy="notifications", cascade={"persist"})
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=true, onDelete="CASCADE")
     */
    public $user;
    /**
     * @ORM\Column(name="type", type="string", length=16)
     */
    public $type;
    /**
     * @ORM\Column(name="object_id", type="string", length=36)
     */
    public $objectId;
}
</code>```

And last, I have a listener than "listen" to "Document" entities (preRemove and postRemove) in order to delete Notification entities. Notification entity isn't linked to Document with a relation because the field "objectId" is generic and it can contains other Entity, depending of the "type" attribute.

Here is my listener :

```<code><?php
namespace CMS\ExtranetBundle\EventListener;

use Doctrine\ORM\Event\LifecycleEventArgs;

class NotificationListener
{
    /**
     * Enregistre l'ID avant la suppression pour l'utiliser dans le postRemove
     *
     * @param LifecycleEventArgs $args
     * @return bool|void
     */
    public function preRemove(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();
        $class  = (new \ReflectionClass($entity))->getShortName();
        if (!$this->isOfValidClass($class)) {
            return;
        }
        $entity->beforeRemoveId = $entity->getId();
    }
    /**
     * Lors de la suppression d'une entité, supprime les notifications correspondantes.
     *
     * @param LifecycleEventArgs $args
     * @return bool|void
     */
    public function postRemove(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();
        $class  = (new \ReflectionClass($entity))->getShortName();
        if (!$this->isOfValidClass($class)) {
            return;
        }
        $id = $entity->beforeRemoveId;
        if (!$id) {
            return;
        }

        $em = $args->getEntityManager();
        $notifications = $em->getRepository('CMSExtranetBundle:Notification')->findBy([
            'type'     => strtolower($class),
            'objectId' => $id
        ]);
        if (count($notifications)) {
            $batchSize = 20;
            $i = 1;
            foreach ($notifications as $notification) {
                $em->remove($notification);
                if (($i % $batchSize) === 0) {
                    $em->flush();
                    $em->clear();
                }
                ++$i;
            }
            // It fails after calling flush()
            $em->flush();
        }
    }
    private function isOfValidClass($class)
    {
        $allowedClasssNames = [
            'Document',
        ];
        foreach ($allowedClasssNames as $allowedClasssName) {
            if ($class == $allowedClasssName) {
                return true;
            }
        }
        return false;
    }
}
</code>```

I'm trying to delete a Folder entity that contains multiples Document.

Here is my controller :

```<code><?php
namespace CMS\ExtranetBundle\Controller;

use Symfony\Component\HttpFoundation\JsonResponse;
use CMS\ExtranetBundle\Entity\Folder;
use CMS\ExtranetBundle\Security\Voters\FolderVoter;

class FolderController extends DefaultController
{
    public function deleteAction(Request $request, Folder $folder)
    {
        // Authorization
        $this->denyAccessUnlessGranted(FolderVoter::WRITE, $folder);
        $em = $this->getDoctrine()->getManager();
        $em->remove($folder);
        $em->flush();
        return new JsonResponse([
            'status'      => true,
        ]);
    }
}
</code>```

My problem is, sometimes, when I delete a Folder, that contain Documents, that have Notification, I got this error :

(Line 73 of NotificationListener.php correspond to the last $em->flush(); after the loop in postRemove)

If the Documents have no Notification, it works

Any idea ?

答:
Ok, thanks to srm` @ #symfony-fr on irc.freenode.net, I changed the way to delete Notification. Here is the postRemove() method of my NotificationListener :

```<code>/**
 * Lors de la suppression d'une entité, supprime les notifications correspondantes.
 *
 * @param LifecycleEventArgs $args
 * @return bool|void
 */
public function postRemove(LifecycleEventArgs $args)
{
    $entity = $args->getEntity();

    // Récupère le nom 'court' de la classe
    $class = (new \ReflectionClass($entity))->getShortName();

    if (!$this->isValidClass($class)) {
        return;
    }
    $id = $entity->beforeRemoveId;
    if (!$id) {
        return;
    }
    $em = $args->getEntityManager();

    $queryBuilder = $em
        ->createQueryBuilder()
        ->delete('CMSExtranetBundle:Notification', 'n')
        ->where('n.type = :type')
        ->andWhere('n.objectId = :objectIds')
        ->setParameter(':type', strtolower($class))
        ->setParameter(':objectIds', $entity->beforeRemoveId);

    $queryBuilder->getQuery()->execute();

}
</code>```

Thanks ! :-D

Body:
I have 3 entities :

Folder :

<?php
namespace CMS\ExtranetBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Folder
 *
 * @ORM\Table(name="folder")
 * @ORM\HasLifecycleCallbacks
 * @ORM\Entity(repositoryClass="CMS\ExtranetBundle\Repository\FolderRepository")
 */
class Folder
{
    /**
     * @ORM\Id
     * @ORM\Column(name="id", type="guid")
     * @ORM\GeneratedValue(strategy="UUID")
     */
    public $id;
    // Used in NotificationListener
    public $beforeRemoveId;
    /**
     * @ORM\OneToMany(targetEntity="Document", mappedBy="folder", cascade={"persist", "remove"})
     */
    public $documents;
}

Document :

<?php
namespace CMS\ExtranetBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Document
 * @ORM\Entity(repositoryClass="CMS\ExtranetBundle\Repository\DocumentRepository")
 * @ORM\Table(name="document")
 * @ORM\HasLifecycleCallbacks
 */
class Document
{
    /**
     * @ORM\Id
     * @ORM\Column(name="id", type="guid")
     * @ORM\GeneratedValue(strategy="UUID")
     */
    public $id;
    /**
     * @ORM\ManyToOne(targetEntity="Folder", inversedBy="documents", cascade={"persist"})
     * @ORM\JoinColumn(name="folder_id", referencedColumnName="id", nullable=true)
     */
    public $folder;
}

and Notification :

<?php
namespace CMS\ExtranetBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Table(name="notification")
 * @ORM\Entity(repositoryClass="CMS\ExtranetBundle\Repository\NotificationRepository")
 * @ORM\HasLifecycleCallbacks
 */
class Notification
{
    /**
     * @ORM\Id
     * @ORM\Column(name="id", type="guid")
     * @ORM\GeneratedValue(strategy="UUID")
     */
    public $id;
    /**
     * @ORM\ManyToOne(targetEntity="User", inversedBy="notifications", cascade={"persist"})
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=true, onDelete="CASCADE")
     */
    public $user;
    /**
     * @ORM\Column(name="type", type="string", length=16)
     */
    public $type;
    /**
     * @ORM\Column(name="object_id", type="string", length=36)
     */
    public $objectId;
}

And last, I have a listener than "listen" to "Document" entities (preRemove and postRemove) in order to delete Notification entities. Notification entity isn't linked to Document with a relation because the field "objectId" is generic and it can contains other Entity, depending of the "type" attribute.

Here is my listener :

<?php
namespace CMS\ExtranetBundle\EventListener;

use Doctrine\ORM\Event\LifecycleEventArgs;

class NotificationListener
{
    /**
     * Enregistre l'ID avant la suppression pour l'utiliser dans le postRemove
     *
     * @param LifecycleEventArgs $args
     * @return bool|void
     */
    public function preRemove(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();
        $class  = (new \ReflectionClass($entity))->getShortName();
        if (!$this->isOfValidClass($class)) {
            return;
        }
        $entity->beforeRemoveId = $entity->getId();
    }
    /**
     * Lors de la suppression d'une entité, supprime les notifications correspondantes.
     *
     * @param LifecycleEventArgs $args
     * @return bool|void
     */
    public function postRemove(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();
        $class  = (new \ReflectionClass($entity))->getShortName();
        if (!$this->isOfValidClass($class)) {
            return;
        }
        $id = $entity->beforeRemoveId;
        if (!$id) {
            return;
        }

        $em = $args->getEntityManager();
        $notifications = $em->getRepository('CMSExtranetBundle:Notification')->findBy([
            'type'     => strtolower($class),
            'objectId' => $id
        ]);
        if (count($notifications)) {
            $batchSize = 20;
            $i = 1;
            foreach ($notifications as $notification) {
                $em->remove($notification);
                if (($i % $batchSize) === 0) {
                    $em->flush();
                    $em->clear();
                }
                ++$i;
            }
            // It fails after calling flush()
            $em->flush();
        }
    }
    private function isOfValidClass($class)
    {
        $allowedClasssNames = [
            'Document',
        ];
        foreach ($allowedClasssNames as $allowedClasssName) {
            if ($class == $allowedClasssName) {
                return true;
            }
        }
        return false;
    }
}

I'm trying to delete a Folder entity that contains multiples Document.

Here is my controller :

<?php
namespace CMS\ExtranetBundle\Controller;

use Symfony\Component\HttpFoundation\JsonResponse;
use CMS\ExtranetBundle\Entity\Folder;
use CMS\ExtranetBundle\Security\Voters\FolderVoter;

class FolderController extends DefaultController
{
    public function deleteAction(Request $request, Folder $folder)
    {
        // Authorization
        $this->denyAccessUnlessGranted(FolderVoter::WRITE, $folder);
        $em = $this->getDoctrine()->getManager();
        $em->remove($folder);
        $em->flush();
        return new JsonResponse([
            'status'      => true,
        ]);
    }
}

My problem is, sometimes, when I delete a Folder, that contain Documents, that have Notification, I got this error :

(Line 73 of NotificationListener.php correspond to the last $em->flush(); after the loop in postRemove)

If the Documents have no Notification, it works

Any idea ?

Body:
Ok, thanks to srm` @ #symfony-fr on irc.freenode.net, I changed the way to delete Notification. Here is the postRemove() method of my NotificationListener :

/**
 * Lors de la suppression d'une entité, supprime les notifications correspondantes.
 *
 * @param LifecycleEventArgs $args
 * @return bool|void
 */
public function postRemove(LifecycleEventArgs $args)
{
    $entity = $args->getEntity();

    // Récupère le nom 'court' de la classe
    $class = (new \ReflectionClass($entity))->getShortName();

    if (!$this->isValidClass($class)) {
        return;
    }
    $id = $entity->beforeRemoveId;
    if (!$id) {
        return;
    }
    $em = $args->getEntityManager();

    $queryBuilder = $em
        ->createQueryBuilder()
        ->delete('CMSExtranetBundle:Notification', 'n')
        ->where('n.type = :type')
        ->andWhere('n.objectId = :objectIds')
        ->setParameter(':type', strtolower($class))
        ->setParameter(':objectIds', $entity->beforeRemoveId);

    $queryBuilder->getQuery()->execute();

}

Thanks ! :-D


问:
How to access non-public fields and inheritent fields in scala
I have a piece of code as below

```<code>object TestReflection {

  def main(args: Array[String]): Unit = {
    val cls = Class.forName("test.Child")
    cls.getDeclaredField("w")
    cls.getDeclaredField("x")
   cls.getDeclaredField("z")
  }
}

class Parent(val x : Int, val t : Int) {

}
class Child(x : Int, z : Int, val w : Int) extends Parent(x, 0) {

}
</code>```

Seems that both cls.getDeclaredField("x") and cls.getDeclaredField("z") don't wok. Anyone know how to access them correctly ?

Thanks

答:
x and z in Child are not variables, they are constructor parameters (i.e. they remain only for the construction and not part of the constructed object) and therefore you cannot access them.

You can access field = cls.getSuperclass.getDeclaredField("x") because x is defined as val in the super class but this is NOT the x in the construction but instead an x inherited from the parent.

To access z you need to assign it to something which survives construction.

Body:
I have a piece of code as below

object TestReflection {

  def main(args: Array[String]): Unit = {
    val cls = Class.forName("test.Child")
    cls.getDeclaredField("w")
    cls.getDeclaredField("x")
   cls.getDeclaredField("z")
  }
}

class Parent(val x : Int, val t : Int) {

}
class Child(x : Int, z : Int, val w : Int) extends Parent(x, 0) {

}

Seems that both cls.getDeclaredField("x") and cls.getDeclaredField("z") don't wok. Anyone know how to access them correctly ?

Thanks


问:
"too many values to unpack error" when trying to create a batch in pyglet
I have been trying to get batches to work in pyglet, but I am completely confused by the error message "too many values to unpack" coming from the pyglet/graphics/__init__.py file. My guess is that that I am doing something wrong syntaxwise when adding the geometry to the batch.

I cut down my code to the essential parts that create the error:

```<code>from pyglet.gl import *
from pyglet.graphics import *
import pyglet

batch = pyglet.graphics.Batch()
img = pyglet.image.load('pic.png')
texture = img.get_texture()

class TextureEnableGroup(pyglet.graphics.Group):
    def set_state(self):
        glEnable(GL_TEXTURE_2D)
    def unset_state(self):
        glDisable(GL_TEXTURE_2D)

texture_enable_group = TextureEnableGroup()

class TextureBindGroup(pyglet.graphics.Group):
    def __init__(self, texture):
        super(TextureBindGroup, self).__init__(parent=texture_enable_group)
        self.texture = texture
    def set_state(self):
        glBindTexture(GL_TEXTURE_2D, self.texture.id)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
    def __eq__(self, other):
        return (self.__class__ is other.__class__ and self.texture == other.__class__)

batch.add(12, GL_TRIANGLES, TextureBindGroup(texture), (('t2f', (0, 0)), ('v3f', (64, 64, 0)), ('t2f', (1, 1)), ('v3f', (-64, -64, 205)), ('t2f', (0, 1)), ('v3f', (-64, 64, 205)), ('t2f', (1, 1)), ('v3f', (64, -64, 205)), ('t2f', (1, 0)), ('v3f', (64, 64, 0)), ('t2f', (0, 1)), ('v3f', (-64, -64, 205))))
</code>```

答:
"Too many values to unpack" is an error you get when you do things like

```<code>a, b = "a b c".split(" ")
</code>```

The split returns three values, but you try to stick them into two.
I guess you have a parenthesis wrong somewhere in that last line. Try to use some clearer syntax for that. As it is now it's quite horrid and unreadable.

Body:
I have been trying to get batches to work in pyglet, but I am completely confused by the error message "too many values to unpack" coming from the pyglet/graphics/__init__.py file. My guess is that that I am doing something wrong syntaxwise when adding the geometry to the batch.

I cut down my code to the essential parts that create the error:

from pyglet.gl import *
from pyglet.graphics import *
import pyglet

batch = pyglet.graphics.Batch()
img = pyglet.image.load('pic.png')
texture = img.get_texture()

class TextureEnableGroup(pyglet.graphics.Group):
    def set_state(self):
        glEnable(GL_TEXTURE_2D)
    def unset_state(self):
        glDisable(GL_TEXTURE_2D)

texture_enable_group = TextureEnableGroup()

class TextureBindGroup(pyglet.graphics.Group):
    def __init__(self, texture):
        super(TextureBindGroup, self).__init__(parent=texture_enable_group)
        self.texture = texture
    def set_state(self):
        glBindTexture(GL_TEXTURE_2D, self.texture.id)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
    def __eq__(self, other):
        return (self.__class__ is other.__class__ and self.texture == other.__class__)

batch.add(12, GL_TRIANGLES, TextureBindGroup(texture), (('t2f', (0, 0)), ('v3f', (64, 64, 0)), ('t2f', (1, 1)), ('v3f', (-64, -64, 205)), ('t2f', (0, 1)), ('v3f', (-64, 64, 205)), ('t2f', (1, 1)), ('v3f', (64, -64, 205)), ('t2f', (1, 0)), ('v3f', (64, 64, 0)), ('t2f', (0, 1)), ('v3f', (-64, -64, 205))))

Body:
"Too many values to unpack" is an error you get when you do things like

a, b = "a b c".split(" ")

The split returns three values, but you try to stick them into two.
I guess you have a parenthesis wrong somewhere in that last line. Try to use some clearer syntax for that. As it is now it's quite horrid and unreadable.


问:
Printing values after a cast to a byte array
I'm trying to understand how to debug data that has been serialized into a byte array. The code shows stripped down problem with failed solution trials.

What I'm trying to achieve is to get a print of the whole array member 12345678 insted of just 78.

```<code>#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>

int main()
{
    uint32_t words[2] = {0x12345678, 0x87654321};
    char * struct_array = &words;

    printf("%x \n", *struct_array);   //  78   prints a lsb byte from the first array member
    printf("%lx \n", *struct_array);   // 78   assuming it would print more than a single byte

    //Perhaps it's printing a single byte because of the char pointer.
    printf("%x \n", (uint32_t) *struct_array);   // 78
    printf("%lx \n", (uint32_t) *struct_array);  // 78
    // Nope
}
</code>```

答:
```<code>//expected it would print more than a single byte
</code>```

That expectation is wrong. The dereference has already been made, and at that time, struct_array was of type char *. The value then (promoted), is used as the argument to the conversion specifier.

To emphasize, the type of argument supplied and  the conversion specifier are not internally related as you might have expected, it's the job of the programmer to get both of these aligned.

If you want the buffer to produce the original value as of the source type, you need to use a cast to get the pointer chaged to the actual type, and then, dereference that to obtain the value. After dereference, the cast makes no sense here.

Word of caution: you can only cast the pointer back to the original type or compatible type thereof, not just "any" other type, that would break strict aliasing.

Body:
I'm trying to understand how to debug data that has been serialized into a byte array. The code shows stripped down problem with failed solution trials.

What I'm trying to achieve is to get a print of the whole array member 12345678 insted of just 78.

#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>

int main()
{
    uint32_t words[2] = {0x12345678, 0x87654321};
    char * struct_array = &words;

    printf("%x \n", *struct_array);   //  78   prints a lsb byte from the first array member
    printf("%lx \n", *struct_array);   // 78   assuming it would print more than a single byte

    //Perhaps it's printing a single byte because of the char pointer.
    printf("%x \n", (uint32_t) *struct_array);   // 78
    printf("%lx \n", (uint32_t) *struct_array);  // 78
    // Nope
}

Body:
//expected it would print more than a single byte

That expectation is wrong. The dereference has already been made, and at that time, struct_array was of type char *. The value then (promoted), is used as the argument to the conversion specifier.

To emphasize, the type of argument supplied and  the conversion specifier are not internally related as you might have expected, it's the job of the programmer to get both of these aligned.

If you want the buffer to produce the original value as of the source type, you need to use a cast to get the pointer chaged to the actual type, and then, dereference that to obtain the value. After dereference, the cast makes no sense here.

Word of caution: you can only cast the pointer back to the original type or compatible type thereof, not just "any" other type, that would break strict aliasing.


问:
TYPO3 query equals by another table
I have TYPO3 7.6.18, and I have problem with query.

this works

```<code>public function getFiltered($offset = 0, $limit = 5){
    $query = $this->createQuery();
    $query->matching($query->equals('cruserId', 3));
    return $query->execute();
</code>```

But this not works

```<code>public function getFiltered($offset = 0, $limit = 5){
    $query = $this->createQuery();
    $query->matching($query->equals('cruserId.uid', 3));

    return $query->execute();
</code>```

this return empty. Why? I filter by condition in another table(fe_users). I  need filter by uid, gender or other fields. I don't know where is a problem.

TCA:

```<code>'cruser_id' => [
    'exclude' => 1,
    'label' => 'LLL:EXT:fefiles/Resources/Private/Language/locallang_db.xlf:tx_fefiles_domain_model_photo.cruser_id',
    'config' => [
        'type' => 'inline',
        'foreign_table' => 'fe_users',
        'minitems' => 0,
        'maxitems' => 1,
        'appearance' => [
            'collapseAll' => 0,
            'levelLinksPosition' => 'top',
            'showSynchronizationLink' => 1,
            'showPossibleLocalizationRecords' => 1,
            'showAllLocalizationLink' => 1
        ],
    ]
],
</code>```

Model:

```<code>  /**
     * CruserId
     *
     * @var \Fhk\Feusersplus\Domain\Model\User
     * @inject
     */
    protected $cruserId;

    /**
     * Returns the cruserId
     *
     * @return \Fhk\Feusersplus\Domain\Model\User $cruserId
     */
    public function getCruserId()
    {
        return $this->cruserId;
    }

    /**
     * Sets the cruserId
     *
     * @return void
     */
    public function setCruserId($cruserId)
    {
        $this->cruserId = $cruserId;
    }
</code>```

If I use cruserId.uid - it just return empty. I had specially create test ext by extension builder and make my model, tca the same, but it return empty. Help me please, good people) Do you now where is problem?

答:
```<code>$query->getQuerySettings()->setRespectStoragePage(false);
        $query->getQuerySettings()->setRespectSysLanguage(false);
</code>```

this solved my problem

Title: TYPO3 query equals by another table

Body:
I have TYPO3 7.6.18, and I have problem with query.

this works

public function getFiltered($offset = 0, $limit = 5){
    $query = $this->createQuery();
    $query->matching($query->equals('cruserId', 3));
    return $query->execute();

But this not works

public function getFiltered($offset = 0, $limit = 5){
    $query = $this->createQuery();
    $query->matching($query->equals('cruserId.uid', 3));

    return $query->execute();

this return empty. Why? I filter by condition in another table(fe_users). I  need filter by uid, gender or other fields. I don't know where is a problem.

TCA:

'cruser_id' => [
    'exclude' => 1,
    'label' => 'LLL:EXT:fefiles/Resources/Private/Language/locallang_db.xlf:tx_fefiles_domain_model_photo.cruser_id',
    'config' => [
        'type' => 'inline',
        'foreign_table' => 'fe_users',
        'minitems' => 0,
        'maxitems' => 1,
        'appearance' => [
            'collapseAll' => 0,
            'levelLinksPosition' => 'top',
            'showSynchronizationLink' => 1,
            'showPossibleLocalizationRecords' => 1,
            'showAllLocalizationLink' => 1
        ],
    ]
],

Model:

  /**
     * CruserId
     *
     * @var \Fhk\Feusersplus\Domain\Model\User
     * @inject
     */
    protected $cruserId;

    /**
     * Returns the cruserId
     *
     * @return \Fhk\Feusersplus\Domain\Model\User $cruserId
     */
    public function getCruserId()
    {
        return $this->cruserId;
    }

    /**
     * Sets the cruserId
     *
     * @return void
     */
    public function setCruserId($cruserId)
    {
        $this->cruserId = $cruserId;
    }

If I use cruserId.uid - it just return empty. I had specially create test ext by extension builder and make my model, tca the same, but it return empty. Help me please, good people) Do you now where is problem?

Body:
$query->getQuerySettings()->setRespectStoragePage(false);
        $query->getQuerySettings()->setRespectSysLanguage(false);

this solved my problem


问:
Ajax call fires success event but returns 201 error
I'm using Ajax on a Laravel project and I have a button that fires a function with two status error and success. but on both of them the success message returns.

Controller:

```<code>if ($user->balance < $total_paid) {
return response()->json(['responseText' => 'error'], 201);
} else {
return response()->json(['responseText' => 'success!'], 200);
}
</code>```

Ajax function in the frontend:

```<code><script type="text/javascript">
            function pay_with_ewallet()    {
            $.ajax({
              url: "{!!URL::route('pay_with_ewallet')!!}",
              type: "post",
              data: {
                'OrderShipAddress':$('input[name=OrderShipAddress]').val(),
                '_token': $('input[name=_token]').val(),
                'OrderEmail':$('input[name=OrderEmail]').val(),
                'city_id':$('select[name=city_id] :selected').val(),
                'OrderPhone':$('input[name=OrderPhone]').val(),
                'shipping_cost': @if (isset( $shipping_total )) {{ $shipping_total  }} @endif ,
                'order_total':@if (isset( $final_total )) {{ $final_total  }} @endif,
                },
                success: function(data) {
                    if (response == 'success')
                        $("#myElem").show();
                        setTimeout(function() { $("#myElem").hide(); }, 10000);
                    else
                        $("#myerror").show();
                        setTimeout(function() { $("#myerror").hide(); }, 10000);
                }
            });
        }
    </script>
</code>```

and the button:

```<code><button href="" class="btn btn-danger pull-right" id="pay_with_ewallet-btn {{ $user->id }}" data-id="{{ $user->id }}" onclick="pay_with_ewallet('pay_with_ewallet{{ $user->id }}')">{{ trans('interface.pay_with_e_wallet') }}</button>
</code>```

I tried whatever I can and a lot of research on the internet but was useless.

答:
201 is an existing HTTP CODE response and means created and a fulfilled request. So for Ajax is a success. Try to use different numbers, out of standars (100-505).

https://httpstatuses.com/201

Body:
I'm using Ajax on a Laravel project and I have a button that fires a function with two status error and success. but on both of them the success message returns.

Controller:

if ($user->balance < $total_paid) {
return response()->json(['responseText' => 'error'], 201);
} else {
return response()->json(['responseText' => 'success!'], 200);
}

Ajax function in the frontend:

and the button:

<button href="" class="btn btn-danger pull-right" id="pay_with_ewallet-btn {{ $user->id }}" data-id="{{ $user->id }}" onclick="pay_with_ewallet('pay_with_ewallet{{ $user->id }}')">{{ trans('interface.pay_with_e_wallet') }}</button>

I tried whatever I can and a lot of research on the internet but was useless.


问:
Is this correct usage of builder pattern in dtos?
Assume i have PostDTO that has this fields:

```<code>private Long id;
private ShortInfoUserDTO author;
private CategoryDTO category;
</code>```

And i have CategoryDTO inside of it that also has Builder, and it has fields:

```<code>private Long id;
private String name;
</code>```

And ShortInfoUserDTO has some fields (doesn't matter what fields, but it also has Builder)

And My builder pattern looks like this ( both CategoryDTO and

```<code>public static Builder builder() {
    return new PostDTO.Builder();
}
public static class Builder {
    PostDTO instance = new PostDTO();

    public Builder id(Long id) {
        instance.id = id;
        return this;
    }

    public Builder author(User user) {
        ShortInfoUserDTO author = ShortInfoUserDTO.builder()
                                                  .id(user.getId())
                                            .username(user.getUsername())
                                            .build();
        instance.author = author;
        return this;
    }

    public Builder category(Category category) {
          CategoryDTO categoryDto = CategoryDTO
                                      .builder()
                                      .id(category.getId())
                                      .name(category.getName())
                                      .build();

          instance.category = categoryDto;
          return this;
    }

    public PostDTO build() {
        return instance;
    }
}
</code>```

Is generally the idea of building author() and category() this way good? like is this proper architecture? One of the reason im asking is because i'm kinda worried about nullpointerexceptions

答:
Well yeah, it is a quite neat way for building your POJO's as long as you can live with this amount of boilerplate code.

Lombok builder can help you reduce the amount of boilerplate.

Another approach is using a mapping tool instead of manual DTO construction. Have a look on ModelMapper for instance.

With mapper you can do something like this:

```<code>public class So44937295ApplicationTests {
    final ModelMapper modelMapper = new ModelMapper();

    @Test
    public void manual() {
        final User user = new User();
        user.setId(42L);
        user.setUsername("John");
        user.setPassword("goof");

        final Category category = new Category();
        category.setId(23L);
        category.setName("Category 1");

        final PostDTO postDTO = new PostDTO();
        postDTO.setAuthor(modelMapper.map(user, ShortInfoUserDTO.class));
        postDTO.setCategory(modelMapper.map(category, CategoryDTO.class));

        assertEquals(user.getId(), postDTO.getAuthor().getId());
        assertEquals(user.getUsername(), postDTO.getAuthor().getUsername());

        assertEquals(category.getId(), postDTO.getCategory().getId());
        assertEquals(category.getName(), postDTO.getCategory().getName());
    }

    @Test
    public void auto() {
        final User user = new User();
        user.setId(42L);
        user.setUsername("John");
        user.setPassword("goof");

        final Category category = new Category();
        category.setId(23L);
        category.setName("Category 1");

        class Post {
            private User author;
            private Category category;
            // getters and setters
        }

        final Post post = new Post();
        post.setAuthor(user);
        post.setCategory(category);
        final PostDTO postDTO = modelMapper.map(post, PostDTO.class);

        assertEquals(post.getAuthor().getId(), postDTO.getAuthor().getId());
        assertEquals(post.getAuthor().getUsername(), postDTO.getAuthor().getUsername());

        assertEquals(post.getCategory().getId(), postDTO.getCategory().getId());
        assertEquals(post.getCategory().getName(), postDTO.getCategory().getName());
    }

    public static class PostDTO {
        private Long id;
        private ShortInfoUserDTO author;
        private CategoryDTO category;
        // getters and setters
    }

    public static class User {
        private Long id;
        private String username;
        private String password;
        // getters and setters
    }

    public static class ShortInfoUserDTO {
        private Long id;
        private String username;
        // getters and setters
    }

    public static class Category {
        private Long id;
        private String name;
        // getters and setters
    }

    public static class CategoryDTO {
        private Long id;
        private String name;
        // getters and setters
    }

}
</code>```

And all transformation logic will be done for you using reflection (based on field names). You can configure that behavior.

Body:
Assume i have PostDTO that has this fields:

private Long id;
private ShortInfoUserDTO author;
private CategoryDTO category;

And i have CategoryDTO inside of it that also has Builder, and it has fields:

private Long id;
private String name;

And ShortInfoUserDTO has some fields (doesn't matter what fields, but it also has Builder)

And My builder pattern looks like this ( both CategoryDTO and

public static Builder builder() {
    return new PostDTO.Builder();
}
public static class Builder {
    PostDTO instance = new PostDTO();

    public Builder id(Long id) {
        instance.id = id;
        return this;
    }

    public Builder author(User user) {
        ShortInfoUserDTO author = ShortInfoUserDTO.builder()
                                                  .id(user.getId())
                                            .username(user.getUsername())
                                            .build();
        instance.author = author;
        return this;
    }

    public Builder category(Category category) {
          CategoryDTO categoryDto = CategoryDTO
                                      .builder()
                                      .id(category.getId())
                                      .name(category.getName())
                                      .build();

          instance.category = categoryDto;
          return this;
    }

    public PostDTO build() {
        return instance;
    }
}

Is generally the idea of building author() and category() this way good? like is this proper architecture? One of the reason im asking is because i'm kinda worried about nullpointerexceptions

Body:
Well yeah, it is a quite neat way for building your POJO's as long as you can live with this amount of boilerplate code.

Lombok builder can help you reduce the amount of boilerplate.

Another approach is using a mapping tool instead of manual DTO construction. Have a look on ModelMapper for instance.

With mapper you can do something like this:

public class So44937295ApplicationTests {
    final ModelMapper modelMapper = new ModelMapper();

    @Test
    public void manual() {
        final User user = new User();
        user.setId(42L);
        user.setUsername("John");
        user.setPassword("goof");

        final Category category = new Category();
        category.setId(23L);
        category.setName("Category 1");

        final PostDTO postDTO = new PostDTO();
        postDTO.setAuthor(modelMapper.map(user, ShortInfoUserDTO.class));
        postDTO.setCategory(modelMapper.map(category, CategoryDTO.class));

        assertEquals(user.getId(), postDTO.getAuthor().getId());
        assertEquals(user.getUsername(), postDTO.getAuthor().getUsername());

        assertEquals(category.getId(), postDTO.getCategory().getId());
        assertEquals(category.getName(), postDTO.getCategory().getName());
    }

    @Test
    public void auto() {
        final User user = new User();
        user.setId(42L);
        user.setUsername("John");
        user.setPassword("goof");

        final Category category = new Category();
        category.setId(23L);
        category.setName("Category 1");

        class Post {
            private User author;
            private Category category;
            // getters and setters
        }

        final Post post = new Post();
        post.setAuthor(user);
        post.setCategory(category);
        final PostDTO postDTO = modelMapper.map(post, PostDTO.class);

        assertEquals(post.getAuthor().getId(), postDTO.getAuthor().getId());
        assertEquals(post.getAuthor().getUsername(), postDTO.getAuthor().getUsername());

        assertEquals(post.getCategory().getId(), postDTO.getCategory().getId());
        assertEquals(post.getCategory().getName(), postDTO.getCategory().getName());
    }

    public static class PostDTO {
        private Long id;
        private ShortInfoUserDTO author;
        private CategoryDTO category;
        // getters and setters
    }

    public static class User {
        private Long id;
        private String username;
        private String password;
        // getters and setters
    }

    public static class ShortInfoUserDTO {
        private Long id;
        private String username;
        // getters and setters
    }

    public static class Category {
        private Long id;
        private String name;
        // getters and setters
    }

    public static class CategoryDTO {
        private Long id;
        private String name;
        // getters and setters
    }

}

And all transformation logic will be done for you using reflection (based on field names). You can configure that behavior.


问:
Is there a special rule for lambda in case of decltype(auto)?
If I understood correctly this answer and referenced standard section [dcl.type.auto.deduct-5], the code:

```<code>decltype(auto) a = e;
</code>```

is always equivalent to

```<code>decltype( e  ) a = e;
</code>```

But now the problem appears if instead of e I put the lambda expression to decltype(auto):

```<code>decltype(auto) lambda = [](){};
</code>```

This compiles, to my surprise, successfully in both gcc and clang. Reason for the shock I've experienced lays in standard which says specifically that lambda should not occur in unevaluated operand [expr.prim.lambda#2] (emphasis mine):

A lambda-expression is a prvalue whose result object is called the
  closure object. A lambda-expression shall not appear in an unevaluated
  operand, in a template-argument, in an alias-declaration, in a typedef
  declaration, or in the declaration of a function or function template
  outside its function body and default arguments.

But as I mentioned the example would be equivalent to:

```<code>decltype([](){}) lambda = [](){};
</code>```

The above code written explicitly obviously would be ill-formed. Of course we could assume that the statement [](){} inside decltype is kind of reference that isn't really a reference like in case of structured bindings, but maybe there is a special rule in standard that I've missed covering lambda initializing decltype(auto)?

答:
This answer is based on my interpretation of the relevant Standard text. Those sections are not very clear with divided opinions, and thus it is currently hard to know the exact meaning of them. It seems that, excluding a possible oversight, the major compilers seem to agree that the definition in question is indeed well-formed.

In addition, it is my opinion that it would be very surprising to hear that the definition were ill-formed.

Reason for the shock I've experienced lays in standard which says specifically that lambda should not occur in unevaluated operand [...]

Where do you see that a lambda appears in an unevaluated context?

```<code>decltype(auto) lambda = [](){};
</code>```

I don't see it, because there is none. The lambda is used as an initializer, which is completely legal.

Now your confusion probably comes about because you seem to think that the above statement is equivalent to

```<code>decltype([](){}) lambda = [](){};
</code>```

That's not the case though, strictly speaking. If you look at the language of the wording, there is a small difference (highlighted by me):

If the placeholder is the decltype(auto) type-specifier, T shall be the placeholder alone. The type deduced for T is determined as described in [dcl.type.simple], as though e had been the operand of the decltype.

The key word here is though. It just means that the deduction happens as if it were decltype(e), meaning that the deduction rules of decltype apply instead of those for auto for the operand e.

Here, the operand e is indeed the lambda, but that is completely legal, because the Standard mandates that the behavior is the same as if you would have written decltype([](){}), meaning that of the rules of decltype deduction apply for the lambda. Now [expr.prim.lambda]/2 doesn't apply here, because the lambda is not in an unevaluated context, so it is actually legal for the compiler to use decltype([](){}) to deduce the type, meaning that the decltype rules have to be used for the lambda.

Sure, if you write decltype([](){}), the program is ill-formed, but that is not the case here, as mentioned above.

In this case, because a lambda expression is a prvalue, the deduced type should just be the type of the lambda.

At least that's how I understand it...

Body:
If I understood correctly this answer and referenced standard section [dcl.type.auto.deduct-5], the code:

decltype(auto) a = e;

is always equivalent to

decltype( e  ) a = e;

But now the problem appears if instead of e I put the lambda expression to decltype(auto):

decltype(auto) lambda = [](){};

This compiles, to my surprise, successfully in both gcc and clang. Reason for the shock I've experienced lays in standard which says specifically that lambda should not occur in unevaluated operand [expr.prim.lambda#2] (emphasis mine):

A lambda-expression is a prvalue whose result object is called the
  closure object. A lambda-expression shall not appear in an unevaluated
  operand, in a template-argument, in an alias-declaration, in a typedef
  declaration, or in the declaration of a function or function template
  outside its function body and default arguments.

But as I mentioned the example would be equivalent to:

decltype([](){}) lambda = [](){};

The above code written explicitly obviously would be ill-formed. Of course we could assume that the statement [](){} inside decltype is kind of reference that isn't really a reference like in case of structured bindings, but maybe there is a special rule in standard that I've missed covering lambda initializing decltype(auto)?

Body:
This answer is based on my interpretation of the relevant Standard text. Those sections are not very clear with divided opinions, and thus it is currently hard to know the exact meaning of them. It seems that, excluding a possible oversight, the major compilers seem to agree that the definition in question is indeed well-formed.

In addition, it is my opinion that it would be very surprising to hear that the definition were ill-formed.

Reason for the shock I've experienced lays in standard which says specifically that lambda should not occur in unevaluated operand [...]

Where do you see that a lambda appears in an unevaluated context?

decltype(auto) lambda = [](){};

I don't see it, because there is none. The lambda is used as an initializer, which is completely legal.

Now your confusion probably comes about because you seem to think that the above statement is equivalent to

decltype([](){}) lambda = [](){};

That's not the case though, strictly speaking. If you look at the language of the wording, there is a small difference (highlighted by me):

If the placeholder is the decltype(auto) type-specifier, T shall be the placeholder alone. The type deduced for T is determined as described in [dcl.type.simple], as though e had been the operand of the decltype.

The key word here is though. It just means that the deduction happens as if it were decltype(e), meaning that the deduction rules of decltype apply instead of those for auto for the operand e.

Here, the operand e is indeed the lambda, but that is completely legal, because the Standard mandates that the behavior is the same as if you would have written decltype([](){}), meaning that of the rules of decltype deduction apply for the lambda. Now [expr.prim.lambda]/2 doesn't apply here, because the lambda is not in an unevaluated context, so it is actually legal for the compiler to use decltype([](){}) to deduce the type, meaning that the decltype rules have to be used for the lambda.

Sure, if you write decltype([](){}), the program is ill-formed, but that is not the case here, as mentioned above.

In this case, because a lambda expression is a prvalue, the deduced type should just be the type of the lambda.

At least that's how I understand it...


问:
CSS3 :target on named tag not working
I am having a hard time getting :target to work on a named tag.

The fiddle is here: https://jsfiddle.net/vgcLartp/1

Any ideas why this is not working?

答:
try this</p>

```<code>:target {
  visibility: visible;
  opacity: 1;
}
</code>```

Title: CSS3 :target on named tag not working

Body:
try this

:target {
  visibility: visible;
  opacity: 1;
}