问:
Sample accurate extraction of chunks of audio using AVFoundation

Problem

I am looking to extract sample-accurate ranges of LPCM audio from audio tracks within video files. Currently, I'm looking to achieve this using AVAssetReaderTrackOutput against an AVAssetTrack delivered from reading a AVURLAsset.

Despite preparing and ensuring the asset is initialized using AVURLAssetPreferPreciseDurationAndTimingKey set to YES, seeking to a sample-accurate position within an asset seems to be inaccurate.

```<code>NSDictionary *options = @{ AVURLAssetPreferPreciseDurationAndTimingKey : @(YES) };
_asset = [[AVURLAsset alloc] initWithURL:fileURL options:options];
</code>```

This manifests itself with e.g. variable bit-rate encoded AAC streams. While I know that VBR audio streams present a performance overhead in seeking accurately, I'm willing to pay this provided I am delivered accurate samples.

When using e.g. Extended Audio File Services and the ExtAudioFileRef APIs, I can achieve sample-accurate seeks and extraction of audio. Likewise with AVAudioFile, as this builds on top of ExtAudioFileRef.

The issue, however, is I would also like to extract audio from media containers that the audio-file only APIs reject, but which are supported in AVFoundation via AVURLAsset.

Method

A sample accurate time range for extraction is defined using CMTime and CMTimeRange, and set on the AVAssetReaderTrackOutput. Samples are then iteratively extracted.

```<code>-(NSData *)readFromFrame:(SInt64)startFrame
      requestedFrameCount:(UInt32)frameCount
{
    NSUInteger expectedByteCount = frameCount * _bytesPerFrame;
    NSMutableData *data = [NSMutableData dataWithCapacity:expectedByteCount];

    //
    // Configure Output
    //

    NSDictionary *settings = @{ AVFormatIDKey               : @( kAudioFormatLinearPCM ),
                                AVLinearPCMIsNonInterleaved : @( NO ),
                                AVLinearPCMIsBigEndianKey   : @( NO ),
                                AVLinearPCMIsFloatKey       : @( YES ),
                                AVLinearPCMBitDepthKey      : @( 32 ),
                                AVNumberOfChannelsKey       : @( 2 ) };

    AVAssetReaderOutput *output = [[AVAssetReaderTrackOutput alloc] initWithTrack:_track outputSettings:settings];

    CMTime startTime    = CMTimeMake( startFrame, _sampleRate );
    CMTime durationTime = CMTimeMake( frameCount, _sampleRate );
    CMTimeRange range   = CMTimeRangeMake( startTime, durationTime );

    //
    // Configure Reader
    //

    NSError *error = nil;
    AVAssetReader *reader = [[AVAssetReader alloc] initWithAsset:_asset error:&error];

    if( !reader )
    {
        fprintf( stderr, "avf : failed to initialize reader\n" );
        fprintf( stderr, "avf : %s\n%s\n", error.localizedDescription.UTF8String, error.localizedFailureReason.UTF8String );
        exit( EXIT_FAILURE );
    }

    [reader addOutput:output];
    [reader setTimeRange:range];
    BOOL startOK = [reader startReading];

    NSAssert( startOK && reader.status == AVAssetReaderStatusReading, @"Ensure we've started reading." );

    NSAssert( _asset.providesPreciseDurationAndTiming, @"We expect the asset to provide accurate timing." );

    //
    // Start reading samples
    //

    CMSampleBufferRef sample = NULL;
    while(( sample = [output copyNextSampleBuffer] ))
    {
        CMTime presentationTime = CMSampleBufferGetPresentationTimeStamp( sample );
        if( data.length == 0 )
        {
            // First read - we should be at the expected presentation time requested.
            int32_t comparisonResult = CMTimeCompare( presentationTime, startTime );
            NSAssert( comparisonResult == 0, @"We expect sample accurate seeking" );
        }

        CMBlockBufferRef buffer = CMSampleBufferGetDataBuffer( sample );

        if( !buffer )
        {
            fprintf( stderr, "avf : failed to obtain buffer" );
            exit( EXIT_FAILURE );
        }

        size_t lengthAtOffset = 0;
        size_t totalLength = 0;
        char *bufferData = NULL;

        if( CMBlockBufferGetDataPointer( buffer, 0, &lengthAtOffset, &totalLength, &bufferData ) != kCMBlockBufferNoErr )
        {
            fprintf( stderr, "avf : failed to get sample\n" );
            exit( EXIT_FAILURE );
        }

        if( bufferData && lengthAtOffset )
        {
            [data appendBytes:bufferData length:lengthAtOffset];
        }

        CFRelease( sample );
    }

    NSAssert( reader.status == AVAssetReaderStatusCompleted, @"Completed reading" );

    [output release];
    [reader release];

    return [NSData dataWithData:data];
}
</code>```

Notes

The presentation time that CMSampleBufferGetPresentationTimeStamp gives me seems to match what I sought after - but as it seems inaccurate, then I have no chance to correct and align the samples I retrieve.

Any thoughts on how to do this?

Alternatively, is there a way to adapt AVAssetTrack to be used by AVAudioFile or ExtAudioFile?

Is it possible to access the audio track via AudioFileOpenWithCallbacks?

Is it possible to get at the audio stream from a video container in a different manner in macOS?

答:
I wrote another answer in which I incorrectly claimed
 AVAssetReader/AVAssetReaderTrackOutput did not do sample accurate seeking, they do, but it looks broken when your audio track is embedded inside a movie file, so you've found a bug. Congratulations!

The audio track dumped with a pass through AVAssetExportSession, as mentioned in a comment on @hotpaw2's answer, works fine, even when you seek on non-packet boundaries (you happened to be seeking on packet boundaries, the linked file's has 1024 frames per packet - seeking off packet boundaries, your diffs are no longer zero, but they are very, very small/non audible) .

I didn't find a workaround, so reconsider dumping the compressed track. Is it that costly?  If you really don't want to do that, you can decode the raw packets yourself by passing nil outputSettings: to your AVAssetReaderOutput and running its output through an AudioQueue or (preferably?) an AudioConverter to get LPCM.

NB in this latter case, you will need to handle rounding up to packet boundaries when seeking.

Body:
Problem

I am looking to extract sample-accurate ranges of LPCM audio from audio tracks within video files. Currently, I'm looking to achieve this using AVAssetReaderTrackOutput against an AVAssetTrack delivered from reading a AVURLAsset.

Despite preparing and ensuring the asset is initialized using AVURLAssetPreferPreciseDurationAndTimingKey set to YES, seeking to a sample-accurate position within an asset seems to be inaccurate.

NSDictionary *options = @{ AVURLAssetPreferPreciseDurationAndTimingKey : @(YES) };
_asset = [[AVURLAsset alloc] initWithURL:fileURL options:options];

This manifests itself with e.g. variable bit-rate encoded AAC streams. While I know that VBR audio streams present a performance overhead in seeking accurately, I'm willing to pay this provided I am delivered accurate samples.

When using e.g. Extended Audio File Services and the ExtAudioFileRef APIs, I can achieve sample-accurate seeks and extraction of audio. Likewise with AVAudioFile, as this builds on top of ExtAudioFileRef.

The issue, however, is I would also like to extract audio from media containers that the audio-file only APIs reject, but which are supported in AVFoundation via AVURLAsset.

Method

A sample accurate time range for extraction is defined using CMTime and CMTimeRange, and set on the AVAssetReaderTrackOutput. Samples are then iteratively extracted.

-(NSData *)readFromFrame:(SInt64)startFrame
      requestedFrameCount:(UInt32)frameCount
{
    NSUInteger expectedByteCount = frameCount * _bytesPerFrame;
    NSMutableData *data = [NSMutableData dataWithCapacity:expectedByteCount];

    //
    // Configure Output
    //

    NSDictionary *settings = @{ AVFormatIDKey               : @( kAudioFormatLinearPCM ),
                                AVLinearPCMIsNonInterleaved : @( NO ),
                                AVLinearPCMIsBigEndianKey   : @( NO ),
                                AVLinearPCMIsFloatKey       : @( YES ),
                                AVLinearPCMBitDepthKey      : @( 32 ),
                                AVNumberOfChannelsKey       : @( 2 ) };

    AVAssetReaderOutput *output = [[AVAssetReaderTrackOutput alloc] initWithTrack:_track outputSettings:settings];

    CMTime startTime    = CMTimeMake( startFrame, _sampleRate );
    CMTime durationTime = CMTimeMake( frameCount, _sampleRate );
    CMTimeRange range   = CMTimeRangeMake( startTime, durationTime );

    //
    // Configure Reader
    //

    NSError *error = nil;
    AVAssetReader *reader = [[AVAssetReader alloc] initWithAsset:_asset error:&error];

    if( !reader )
    {
        fprintf( stderr, "avf : failed to initialize reader\n" );
        fprintf( stderr, "avf : %s\n%s\n", error.localizedDescription.UTF8String, error.localizedFailureReason.UTF8String );
        exit( EXIT_FAILURE );
    }

    [reader addOutput:output];
    [reader setTimeRange:range];
    BOOL startOK = [reader startReading];

    NSAssert( startOK && reader.status == AVAssetReaderStatusReading, @"Ensure we've started reading." );

    NSAssert( _asset.providesPreciseDurationAndTiming, @"We expect the asset to provide accurate timing." );

    //
    // Start reading samples
    //

    CMSampleBufferRef sample = NULL;
    while(( sample = [output copyNextSampleBuffer] ))
    {
        CMTime presentationTime = CMSampleBufferGetPresentationTimeStamp( sample );
        if( data.length == 0 )
        {
            // First read - we should be at the expected presentation time requested.
            int32_t comparisonResult = CMTimeCompare( presentationTime, startTime );
            NSAssert( comparisonResult == 0, @"We expect sample accurate seeking" );
        }

        CMBlockBufferRef buffer = CMSampleBufferGetDataBuffer( sample );

        if( !buffer )
        {
            fprintf( stderr, "avf : failed to obtain buffer" );
            exit( EXIT_FAILURE );
        }

        size_t lengthAtOffset = 0;
        size_t totalLength = 0;
        char *bufferData = NULL;

        if( CMBlockBufferGetDataPointer( buffer, 0, &lengthAtOffset, &totalLength, &bufferData ) != kCMBlockBufferNoErr )
        {
            fprintf( stderr, "avf : failed to get sample\n" );
            exit( EXIT_FAILURE );
        }

        if( bufferData && lengthAtOffset )
        {
            [data appendBytes:bufferData length:lengthAtOffset];
        }

        CFRelease( sample );
    }

    NSAssert( reader.status == AVAssetReaderStatusCompleted, @"Completed reading" );

    [output release];
    [reader release];

    return [NSData dataWithData:data];
}

Notes

The presentation time that CMSampleBufferGetPresentationTimeStamp gives me seems to match what I sought after - but as it seems inaccurate, then I have no chance to correct and align the samples I retrieve.

Any thoughts on how to do this?

Alternatively, is there a way to adapt AVAssetTrack to be used by AVAudioFile or ExtAudioFile?

Is it possible to access the audio track via AudioFileOpenWithCallbacks?

Is it possible to get at the audio stream from a video container in a different manner in macOS?


来源: stackexchange

问:
log4j2 Modify stacktrace format
Is it possible to configure log4j2 in such a way that the stacktraces don't show the source and maybe not the line numbers?

In case you are wondering why I would want that, I need this for unit tests, that need to test if exceptions get logged correctly. So if for example the JRE version is not the same as the one I copied the original stacktrace, from the tests fail. So if the source wasn't included in the stacktrace it would be a lot more version independend.

Example:

Currently a line from the stacktrace looks like this:

```<code>    at java.lang.Object.wait(Object.java:502) ~[?:1.8.0_144]
</code>```

I would like it to look like this (but only for log4j2):

```<code>    at java.lang.Object.wait(Object.java:502)
</code>```

Maybe even like this:

```<code>    at java.lang.Object.wait(Object.java)
</code>```

Or even shorter:

```<code>    at java.lang.Object.wait
</code>```

(Any of the shortened versions would be acceptable. As currently only the source (~[?:1.8.0_144] vs ~[?:1.8.0_151] for example) differs.)

Update:

I just found this in the offical documentation: https://logging.apache.org/log4j/2.x/manual/layouts.html#Patterns I think using %ex{full} should be what I want. Will test it.

There are also several other available formats.

答: I don't think it's possible. The stacktrace comes from the JVM, log4j just prints whatever it is given. </p>

ContentLicense: CC BY-SA 3.0

Title: log4j2 Modify stacktrace format

Body:
Is it possible to configure log4j2 in such a way that the stacktraces don't show the source and maybe not the line numbers?

In case you are wondering why I would want that, I need this for unit tests, that need to test if exceptions get logged correctly. So if for example the JRE version is not the same as the one I copied the original stacktrace, from the tests fail. So if the source wasn't included in the stacktrace it would be a lot more version independend.

Example:

Currently a line from the stacktrace looks like this:

    at java.lang.Object.wait(Object.java:502) ~[?:1.8.0_144]

I would like it to look like this (but only for log4j2):

    at java.lang.Object.wait(Object.java:502)

Maybe even like this:

    at java.lang.Object.wait(Object.java)

Or even shorter:

    at java.lang.Object.wait

(Any of the shortened versions would be acceptable. As currently only the source (~[?:1.8.0_144] vs ~[?:1.8.0_151] for example) differs.)

Update:

I just found this in the offical documentation: https://logging.apache.org/log4j/2.x/manual/layouts.html#Patterns I think using %ex{full} should be what I want. Will test it.

There are also several other available formats.


问:
Oracle SQL Count Grouping by without repeating records in previous days
I need to count the distinct WO grouping by day, but not counting the WO that were already in previous days. And sum the LABOR column grouping by day also.

SAMPLE:

```<code>DAY   WO     LABOR
6   379157    3
9   379157    5
10  379404    8
10  379362    8
19  386118    10
24  386547    2
25  388711    8
25  386547    5
30  386547    1
</code>```

RESULTS

```<code>DAY   WO    LABOR
6      1    3
9      0    5
10     2    16
19     1    10
24     1    2
25     1    13
30     0    1
</code>```

Thanks a lot for your help

答:
I think you should GROUP BY WO, and retrieve the MIN day that that WO occurred in as one subquery. The former is essentially is a re-statement of your first requirement. Instead of looking at the WO and trying to exclude WO that appeared on previous days, it can be thought of as "a WO should really only be valid the first time it's seen on any day == the value of WO and the first day (min day) it appeared on"

Then this data set should be joined with another data set that is the sum of the labor on all the days.

Because there are going to be more days in the subquery that sums the labor (there'll be one day for every day that appears in the source) but not necessarily as many days coming out of the query that selects the min day per wo, the query with the more days should serve as the left hand side of a left join

```<code>SELECT
  labors.day, count(wo), min(sumlabor)
FROM
(
  SELECT day, sum(labor) as sumlabor FROM t GROUP BY day
) labors
LEFT OUTER JOIN
(
  SELECT wo, min(day) as day FROM t GROUP BY wo
) wos
ON
  wos.day = labors.day

GROUP BY
  labors.day
</code>```

Hopefully the explanation of how I thought about your problem, and how I then wrote a query from it, will help you think about similar problems in the future - sometimes it's easier to turn logic on its head/state it another way, before writing a query from it

Body:
I need to count the distinct WO grouping by day, but not counting the WO that were already in previous days. And sum the LABOR column grouping by day also.

SAMPLE:

DAY   WO     LABOR
6   379157    3
9   379157    5
10  379404    8
10  379362    8
19  386118    10
24  386547    2
25  388711    8
25  386547    5
30  386547    1

RESULTS

DAY   WO    LABOR
6      1    3
9      0    5
10     2    16
19     1    10
24     1    2
25     1    13
30     0    1

Thanks a lot for your help

Body:
I think you should GROUP BY WO, and retrieve the MIN day that that WO occurred in as one subquery. The former is essentially is a re-statement of your first requirement. Instead of looking at the WO and trying to exclude WO that appeared on previous days, it can be thought of as "a WO should really only be valid the first time it's seen on any day == the value of WO and the first day (min day) it appeared on"

Then this data set should be joined with another data set that is the sum of the labor on all the days.

Because there are going to be more days in the subquery that sums the labor (there'll be one day for every day that appears in the source) but not necessarily as many days coming out of the query that selects the min day per wo, the query with the more days should serve as the left hand side of a left join

SELECT
  labors.day, count(wo), min(sumlabor)
FROM
(
  SELECT day, sum(labor) as sumlabor FROM t GROUP BY day
) labors
LEFT OUTER JOIN
(
  SELECT wo, min(day) as day FROM t GROUP BY wo
) wos
ON
  wos.day = labors.day

GROUP BY
  labors.day

Hopefully the explanation of how I thought about your problem, and how I then wrote a query from it, will help you think about similar problems in the future - sometimes it's easier to turn logic on its head/state it another way, before writing a query from it


问:
AngularJS format JSON string output
I have an AngularJS application, which collects data from input, transforms a model into a string using JSON.stringify() and lets a user edit this model in such a way that input fields get updated if the <textarea> element is updated and vice versa. Some kind of two-way binding :)

The problem is that the String itself looks ugly and I would like to format it so it looks like this:

And not like it looks now:

Any ideas how this can be accomplished? If you need some additional info - don't hesitate asking. Every answer is highly appreciated and answered immediately.

Thank you.

P.S. I guess this should be some kind of directive or a custom filter. Data itself SHOULD NOT be changed, only the output.

答:
I guess you want to use  to edit the json text.
Then you can use ivarni's way:
    ```{{data | json}}```
and add an adition attribute to make ``` editable</p>

<code><pre contenteditable="true">{{data | json}}```
```

Hope this can help you.

ContentLicense: CC BY-SA 4.0

Title: AngularJS format JSON string output

Body:
I guess you want to use  to edit the json text.
Then you can use ivarni's way:

{{data | json}}

and add an adition attribute to make
 editable

<pre contenteditable="true">{{data | json}}</pre>

Hope this can help you.


问:
How to send data using TCP socket in windows for Spark Structured Streaming
I want to create and send data using a TCP socket so that I can use that as a Streaming source for Spark Structured Streaming. I am using Windows OS. I tried using Putty to SSH to my localhost but that is asking for login and password which I don't know what to give.

Can anyone please help me to achieve this.
Thanks in Advance !!

答:
Here I got my answer. Just follow these steps:

Install netcat from [here][1]

After Downloading netcat go to the netcat directory installed and open it in cmd.

now run: nc -l -p [YourPortNumber]

Now run the following Spark Structured streaming code

   val df = spark
         .readStream
         .format("socket")
         .option("host", "your host")
         .option("port", "your port")
         .load()

   df.selectExpr("CAST(value AS STRING)")
     .writeStream
     .format("console")
     .option("truncate", "false")
     .start()
     .awaitTermination()
```
</li>
<li><p>Now start typing your data in the cmd window where your socket was listening to.</p>
</li>
</ol>
<p>If you want to check whether your port is listening to the mentioned port no. go to the cmd window and type:</p>
```telnet yourhost yourport
```

and enter. Now start typing and see whether data is getting received to your previous cmd-window where you were listening to the port. Data must be input into the window where you were running the "netcat" application, from.

Be aware that not all ports allow this listening; in my system "9999" did and "4444" did not.
[1]: https://linhost.info/2011/05/netcat-for-windows/

Body:
Here I got my answer. Just follow these steps:

Install netcat from [here][1]

After Downloading netcat go to the netcat directory installed and open it in cmd.

now run: nc -l -p [YourPortNumber]

Now run the following Spark Structured streaming code

   val df = spark
         .readStream
         .format("socket")
         .option("host", "your host")
         .option("port", "your port")
         .load()

   df.selectExpr("CAST(value AS STRING)")
     .writeStream
     .format("console")
     .option("truncate", "false")
     .start()
     .awaitTermination()

Now start typing your data in the cmd window where your socket was listening to.

If you want to check whether your port is listening to the mentioned port no. go to the cmd window and type:

telnet yourhost yourport

and enter. Now start typing and see whether data is getting received to your previous cmd-window where you were listening to the port. Data must be input into the window where you were running the "netcat" application, from.

Be aware that not all ports allow this listening; in my system "9999" did and "4444" did not.
[1]: https://linhost.info/2011/05/netcat-for-windows/


问:
How to save dynamically added div elements?
This function add new div dynamically:

$(document).ready(function() {
  i = '1';
  x = '0';

  $("#btn3").click(function() {
    i++;
    x++;

    z = x * 2;
    r = z + 1;

    $('

Obwód ' + i + '  <button class="btn btn-block btn-lg btn-primary" type="button" id=' + z + ' onClick="relayClick(this.id)">Wł</button> <button class="btn btn-block btn-lg btn-danger" type="button" id=' + r + ' onClick="relayClick(this.id)">Wył</button>

').appendTo("#container");
  });
});
```

How can I save the new created "div" ? New "div" must be visible after refreshing page.

答:
You can save your html content with localStorage:

Save:

```<code>  var html = $('#container').html();
  window.localStorage.setItem('content',html);
</code>```

Read:

```<code>$('#container').html(window.localStorage.getItem('content'));
</code>```

JSFiddle

And if you want to empty localStorage go with this:

```<code>window.localStorage.removeItem('content');
</code>```

Or

JSFiddle

Body:
This function add new div dynamically:

$(document).ready(function() {
  i = '1';
  x = '0';

  $("#btn3").click(function() {
    i++;
    x++;

    z = x * 2;
    r = z + 1;

    $('

Obwód ' + i + '  <button class="btn btn-block btn-lg btn-primary" type="button" id=' + z + ' onClick="relayClick(this.id)">Wł</button> <button class="btn btn-block btn-lg btn-danger" type="button" id=' + r + ' onClick="relayClick(this.id)">Wył</button>

').appendTo("#container");
  });
});

How can I save the new created "div" ? New "div" must be visible after refreshing page.

Body:
You can save your html content with localStorage:

Save:

  var html = $('#container').html();
  window.localStorage.setItem('content',html);

Read:

$('#container').html(window.localStorage.getItem('content'));

JSFiddle

And if you want to empty localStorage go with this:

window.localStorage.removeItem('content');

Or

JSFiddle


问:
Is it possible to output a VPC peering connection request id using CloudFormation template?
I wrote a CloudFormation template, which among other stuff also creates a VPC peering connection.

If you are familiar with VPC peerings then you know that after the creation, a request is created and waiting for approval.

I'd like to add to the outputs portion of the CloudFormation template the VPC peering connection request id.

Is that possible? I couldn't find the way...

Edit:

This is the relevant portion of the template:

```<code>"Resources" : {
  "VPC": {
    "Type" : "AWS::EC2::VPC",
    "Description" : "Choose which VPC the security groups should be deployed to",
    "Properties" : {
      "CidrBlock" : "172.51.0.0/16",
      "EnableDnsSupport" : "true",
      "EnableDnsHostnames" : "true",
      "InstanceTenancy" : "default"
    }
  },

  "VPCPeering" : {
    "Type" : "AWS::EC2::VPCPeeringConnection",
    "Properties" : {
      "PeerVpcId" : "vpc-2XXXXXb",
      "VpcId" : { "Ref" : "VPC" }
    }
  },
</code>```

I'm using Jenkins with the CloudFormation plugin to issue the creation of a new stack.

I want the new stack to automatically create peering between the VPC that the stack creates and the existing management VPC.

My plan was to issue the creation through the template, and then once the creation completes, I intended to use AWS Cli (from Jenkins) to accept the peering request and since this step requires me to know the vpc peering request id, then I wanted to output it using the "Outputs" : {} section of the template.

Can it be done?

答: No it is not possible. CloudFormation only supports VPC Peering where peering is automatically approved (i.e. within the same account) or where you specify a role you can assume to automatically approve the peer.</p>

Body:
I wrote a CloudFormation template, which among other stuff also creates a VPC peering connection.

If you are familiar with VPC peerings then you know that after the creation, a request is created and waiting for approval.

I'd like to add to the outputs portion of the CloudFormation template the VPC peering connection request id.

Is that possible? I couldn't find the way...

Edit:

This is the relevant portion of the template:

"Resources" : {
  "VPC": {
    "Type" : "AWS::EC2::VPC",
    "Description" : "Choose which VPC the security groups should be deployed to",
    "Properties" : {
      "CidrBlock" : "172.51.0.0/16",
      "EnableDnsSupport" : "true",
      "EnableDnsHostnames" : "true",
      "InstanceTenancy" : "default"
    }
  },

  "VPCPeering" : {
    "Type" : "AWS::EC2::VPCPeeringConnection",
    "Properties" : {
      "PeerVpcId" : "vpc-2XXXXXb",
      "VpcId" : { "Ref" : "VPC" }
    }
  },

I'm using Jenkins with the CloudFormation plugin to issue the creation of a new stack.

I want the new stack to automatically create peering between the VPC that the stack creates and the existing management VPC.

My plan was to issue the creation through the template, and then once the creation completes, I intended to use AWS Cli (from Jenkins) to accept the peering request and since this step requires me to know the vpc peering request id, then I wanted to output it using the "Outputs" : {} section of the template.

Can it be done?


问:
Are these 2 statements the same?
Do these 2 statements mean the same thing?

```<code>if ($host eq '') {
    print "Host exists\n";
}
</code>```

And

```<code>if (defined $host) {
    print "Host exists\n";
}
</code>```

答: No, they are different. One is comparing $host to the empty string, and the other is checking to see whether $host is defined at all (and may have any value).

ContentLicense: CC BY-SA 2.5

Title: Are these 2 statements the same?

Body:
Do these 2 statements mean the same thing?

if ($host eq '') {
    print "Host exists\n";
}

And

if (defined $host) {
    print "Host exists\n";
}


问:
Shiny dynamic content based on window size (like css media query)
I have some plots in a panel. I want to change them into tabsetpanel when the window width is small. Is there any way in shiny to determine window width of browser. For example, in the following example, how can I switch uiOutput from plotPanel1 to plotPanel2 when the window width is large enough.

```<code>library(ggplot2)

ui <- fluidPage(
  title = "TestApp",
  h1("Test Application"),
  sidebarLayout(
    sidebarPanel(
      sliderInput("bins", "Bins", 2, 20, 1, value = 10)
    ),
    mainPanel(
      fluidRow(
        uiOutput("plotPanel1")
      )
    )
  )
)
server <- function(input, output, session){
  output$plot1 <- renderPlot({
    mdl <- lm(mpg ~ ., data = mtcars)
    ggplot(mdl, aes(.resid)) + geom_histogram(bins = input$bins)
  }, res = 110)
  output$plot2 <- renderPlot({
    mdl <- lm(UrbanPop ~ ., data = USArrests)
    ggplot(mdl, aes(.resid)) + geom_histogram(bins = input$bins)
  }, res = 110)
  output$plot3 <- renderPlot({
    mdl <- lm(uptake ~ ., data = CO2)
    ggplot(mdl, aes(.resid)) + geom_histogram(bins = input$bins)
  }, res = 110)
  output$plotPanel1 <- renderUI({
    tabsetPanel(
      tabPanel(
        "plot1",
        plotOutput("plot1")
      ),
      tabPanel(
        "plot2",
        plotOutput("plot2")
      ),
      tabPanel(
        "plot3",
        plotOutput("plot3")
      )
    )
  })
  output$plotPanel2 <- renderUI({
    fluidRow(
      column(
        4,
        plotOutput("plot1")
      ),
      column(
        4,
        plotOutput("plot2")
      ),
      column(
        4,
        plotOutput("plot3")
      )
    )
  })
}

runApp(shinyApp(ui, server))
</code>```

答:
Since Shiny is generating a bunch of HTML you could use media-query, or another possibility is to use javaScript and get the width of the window. I had some trouble with the css solution, but I will show you both:

Approach #1 (Working): Using javaScript

With javaScript you can define an input element based on the width of the window:

```<code>  tags$head(tags$script('
                        var width = 0;
                        $(document).on("shiny:connected", function(e) {
                          width = window.innerWidth;
                          Shiny.onInputChange("width", width);
                        });
                        $(window).resize(function(e) {
                          width = window.innerWidth;
                          Shiny.onInputChange("width", width);
                        });
                        '))
</code>```

If this script is included in the UI, you can then access input$width to obtain the width of the window. (Disclaimer: I used the accepted answer in the following SO topic for the JS code.)

I added an observer to check the width. If it is below/above a certain threshold then the elements are shown/hidden.

```<code>  observe( {
    req(input$width)
    if(input$width < 800) {
      shinyjs::show("plotPanel1")
      shinyjs::hide("plotPanel2")
    } else {
      shinyjs::hide("plotPanel1")
      shinyjs::show("plotPanel2")
    }
  })
</code>```

Full code:

```<code>library(shinyjs)
library(ggplot2)

ui <- fluidPage(
  useShinyjs(),
  title = "TestApp",
  h1("Test Application"),
  sidebarLayout(
    sidebarPanel(
      sliderInput("bins", "Bins", 2, 20, 1, value = 10)
    ),
    mainPanel(
      fluidRow(
        div(id="p1", uiOutput("plotPanel1")),
        div(id="p2", uiOutput("plotPanel2"))
      )
    )
  ),
  tags$head(tags$script('
                        var width = 0;
                        $(document).on("shiny:connected", function(e) {
                          width = window.innerWidth;
                          Shiny.onInputChange("width", width);
                        });
                        $(window).resize(function(e) {
                          width = window.innerWidth;
                          Shiny.onInputChange("width", width);
                        });
                        '))
)

server <- function(input, output, session){
  plot1 <- reactive({
    ggplot(lm(mpg ~ ., data = mtcars), aes(.resid)) +
      geom_histogram(bins = input$bins)
  })
  plot2 <- reactive({
    ggplot(lm(UrbanPop ~ ., data = USArrests), aes(.resid)) +
      geom_histogram(bins = input$bins)
  })
  plot3 <- reactive({
    ggplot(lm(uptake ~ ., data = CO2), aes(.resid)) +
      geom_histogram(bins = input$bins)
  })

  output$plotPanel1 <- renderUI({
    tagList(
      tabsetPanel(
        tabPanel(
          "plot1",
          renderPlot(plot1())
        ),
        tabPanel(
          "plot2",
          renderPlot(plot2())
        ),
        tabPanel(
          "plot3",
          renderPlot(plot3())
        )
      )
    )
  })

  output$plotPanel2 <- renderUI({
    tagList(
      fluidRow(
        column(
          4,
          renderPlot(plot1())
        ),
        column(
          4,
          renderPlot(plot2())
        ),
        column(
          4,
          renderPlot(plot3())
        )
      )
    )
  })

  observe( {
    req(input$width)
    if(input$width < 800) {
      shinyjs::show("plotPanel1")
      shinyjs::hide("plotPanel2")
    } else {
      shinyjs::hide("plotPanel1")
      shinyjs::show("plotPanel2")
    }
  })
}

runApp(shinyApp(ui, server))
</code>```

This is not a perfect solution in my opinion, since we are rendering every plot twice, however you can probably build on this.

Approach #2 (NOT working): CSS and media-query

You can control the display attribute within a media-query in tags$head. It works fine for any element, however I found that it doesn't work well with UIOutput.

Working example for simple div with text:

```<code>ui <- fluidPage(
  tags$head(
    tags$style(HTML("
      @media screen and (min-width: 1000px) {
        #p1 {
          display: none;
        }

        #p2 {
          display: block;
        }
      }

      @media screen and (max-width: 1000px) {
        #p1 {
          display: block;
        }

        #p2 {
          display: none;
        }
      }
      "
    ))
    ),
    div(id="p1", "First element"),
    div(id="p2", "Second element")
)
</code>```

Not working example for UIOutput:

```<code>ui <- fluidPage(
  title = "TestApp",
  h1("Test Application"),
  sidebarLayout(
    sidebarPanel(
      sliderInput("bins", "Bins", 2, 20, 1, value = 10)
    ),
    mainPanel(
      fluidRow(
          div(id="p1", uiOutput("plotPanel1")),
          div(id="p2", uiOutput("plotPanel2"))
      )
    )
  ),
  tags$head(
    tags$style(HTML("
      @media screen and (min-width: 1000px) {
        #plotPanel1 {
          display: none;
        }

        #plotPanel2 {
          display: block;
        }
      }

      @media screen and (max-width: 1000px) {
        #plotPanel1 {
          display: block;
        }

        #plotPanel2 {
          display: none;
        }
      }
      "
    ))
    )
)
server <- function(input, output, session){
  plot1 <- reactive({
    ggplot(lm(mpg ~ ., data = mtcars), aes(.resid)) +
      geom_histogram(bins = input$bins)
  })
  plot2 <- reactive({
    ggplot(lm(UrbanPop ~ ., data = USArrests), aes(.resid)) +
      geom_histogram(bins = input$bins)
  })
  plot3 <- reactive({
    ggplot(lm(uptake ~ ., data = CO2), aes(.resid)) +
      geom_histogram(bins = input$bins)
  })

  output$plotPanel1 <- renderUI({
    tagList(
      tabsetPanel(
        tabPanel(
          "plot1",
          renderPlot(plot1())
        ),
        tabPanel(
          "plot2",
          renderPlot(plot2())
        ),
        tabPanel(
          "plot3",
          renderPlot(plot3())
        )
      )
    )
  })
  output$plotPanel2 <- renderUI({
    tagList(
      fluidRow(
        column(
          4,
          renderPlot(plot1())
        ),
        column(
          4,
          renderPlot(plot2())
        ),
        column(
          4,
          renderPlot(plot3())
        )
      )
    )
  })
}

runApp(shinyApp(ui, server))
</code>```

Body:
I have some plots in a panel. I want to change them into tabsetpanel when the window width is small. Is there any way in shiny to determine window width of browser. For example, in the following example, how can I switch uiOutput from plotPanel1 to plotPanel2 when the window width is large enough.

library(ggplot2)

ui <- fluidPage(
  title = "TestApp",
  h1("Test Application"),
  sidebarLayout(
    sidebarPanel(
      sliderInput("bins", "Bins", 2, 20, 1, value = 10)
    ),
    mainPanel(
      fluidRow(
        uiOutput("plotPanel1")
      )
    )
  )
)
server <- function(input, output, session){
  output$plot1 <- renderPlot({
    mdl <- lm(mpg ~ ., data = mtcars)
    ggplot(mdl, aes(.resid)) + geom_histogram(bins = input$bins)
  }, res = 110)
  output$plot2 <- renderPlot({
    mdl <- lm(UrbanPop ~ ., data = USArrests)
    ggplot(mdl, aes(.resid)) + geom_histogram(bins = input$bins)
  }, res = 110)
  output$plot3 <- renderPlot({
    mdl <- lm(uptake ~ ., data = CO2)
    ggplot(mdl, aes(.resid)) + geom_histogram(bins = input$bins)
  }, res = 110)
  output$plotPanel1 <- renderUI({
    tabsetPanel(
      tabPanel(
        "plot1",
        plotOutput("plot1")
      ),
      tabPanel(
        "plot2",
        plotOutput("plot2")
      ),
      tabPanel(
        "plot3",
        plotOutput("plot3")
      )
    )
  })
  output$plotPanel2 <- renderUI({
    fluidRow(
      column(
        4,
        plotOutput("plot1")
      ),
      column(
        4,
        plotOutput("plot2")
      ),
      column(
        4,
        plotOutput("plot3")
      )
    )
  })
}

runApp(shinyApp(ui, server))

Body:
Since Shiny is generating a bunch of HTML you could use media-query, or another possibility is to use javaScript and get the width of the window. I had some trouble with the css solution, but I will show you both:

Approach #1 (Working): Using javaScript

With javaScript you can define an input element based on the width of the window:

  tags$head(tags$script('
                        var width = 0;
                        $(document).on("shiny:connected", function(e) {
                          width = window.innerWidth;
                          Shiny.onInputChange("width", width);
                        });
                        $(window).resize(function(e) {
                          width = window.innerWidth;
                          Shiny.onInputChange("width", width);
                        });
                        '))

If this script is included in the UI, you can then access input$width to obtain the width of the window. (Disclaimer: I used the accepted answer in the following SO topic for the JS code.)

I added an observer to check the width. If it is below/above a certain threshold then the elements are shown/hidden.

  observe( {
    req(input$width)
    if(input$width < 800) {
      shinyjs::show("plotPanel1")
      shinyjs::hide("plotPanel2")
    } else {
      shinyjs::hide("plotPanel1")
      shinyjs::show("plotPanel2")
    }
  })

Full code:

library(shinyjs)
library(ggplot2)

ui <- fluidPage(
  useShinyjs(),
  title = "TestApp",
  h1("Test Application"),
  sidebarLayout(
    sidebarPanel(
      sliderInput("bins", "Bins", 2, 20, 1, value = 10)
    ),
    mainPanel(
      fluidRow(
        div(id="p1", uiOutput("plotPanel1")),
        div(id="p2", uiOutput("plotPanel2"))
      )
    )
  ),
  tags$head(tags$script('
                        var width = 0;
                        $(document).on("shiny:connected", function(e) {
                          width = window.innerWidth;
                          Shiny.onInputChange("width", width);
                        });
                        $(window).resize(function(e) {
                          width = window.innerWidth;
                          Shiny.onInputChange("width", width);
                        });
                        '))
)

server <- function(input, output, session){
  plot1 <- reactive({
    ggplot(lm(mpg ~ ., data = mtcars), aes(.resid)) +
      geom_histogram(bins = input$bins)
  })
  plot2 <- reactive({
    ggplot(lm(UrbanPop ~ ., data = USArrests), aes(.resid)) +
      geom_histogram(bins = input$bins)
  })
  plot3 <- reactive({
    ggplot(lm(uptake ~ ., data = CO2), aes(.resid)) +
      geom_histogram(bins = input$bins)
  })

  output$plotPanel1 <- renderUI({
    tagList(
      tabsetPanel(
        tabPanel(
          "plot1",
          renderPlot(plot1())
        ),
        tabPanel(
          "plot2",
          renderPlot(plot2())
        ),
        tabPanel(
          "plot3",
          renderPlot(plot3())
        )
      )
    )
  })

  output$plotPanel2 <- renderUI({
    tagList(
      fluidRow(
        column(
          4,
          renderPlot(plot1())
        ),
        column(
          4,
          renderPlot(plot2())
        ),
        column(
          4,
          renderPlot(plot3())
        )
      )
    )
  })

  observe( {
    req(input$width)
    if(input$width < 800) {
      shinyjs::show("plotPanel1")
      shinyjs::hide("plotPanel2")
    } else {
      shinyjs::hide("plotPanel1")
      shinyjs::show("plotPanel2")
    }
  })
}

runApp(shinyApp(ui, server))

This is not a perfect solution in my opinion, since we are rendering every plot twice, however you can probably build on this.

Approach #2 (NOT working): CSS and media-query

You can control the display attribute within a media-query in tags$head. It works fine for any element, however I found that it doesn't work well with UIOutput.

Working example for simple div with text:

ui <- fluidPage(
  tags$head(
    tags$style(HTML("
      @media screen and (min-width: 1000px) {
        #p1 {
          display: none;
        }

        #p2 {
          display: block;
        }
      }

      @media screen and (max-width: 1000px) {
        #p1 {
          display: block;
        }

        #p2 {
          display: none;
        }
      }
      "
    ))
    ),
    div(id="p1", "First element"),
    div(id="p2", "Second element")
)

Not working example for UIOutput:

ui <- fluidPage(
  title = "TestApp",
  h1("Test Application"),
  sidebarLayout(
    sidebarPanel(
      sliderInput("bins", "Bins", 2, 20, 1, value = 10)
    ),
    mainPanel(
      fluidRow(
          div(id="p1", uiOutput("plotPanel1")),
          div(id="p2", uiOutput("plotPanel2"))
      )
    )
  ),
  tags$head(
    tags$style(HTML("
      @media screen and (min-width: 1000px) {
        #plotPanel1 {
          display: none;
        }

        #plotPanel2 {
          display: block;
        }
      }

      @media screen and (max-width: 1000px) {
        #plotPanel1 {
          display: block;
        }

        #plotPanel2 {
          display: none;
        }
      }
      "
    ))
    )
)
server <- function(input, output, session){
  plot1 <- reactive({
    ggplot(lm(mpg ~ ., data = mtcars), aes(.resid)) +
      geom_histogram(bins = input$bins)
  })
  plot2 <- reactive({
    ggplot(lm(UrbanPop ~ ., data = USArrests), aes(.resid)) +
      geom_histogram(bins = input$bins)
  })
  plot3 <- reactive({
    ggplot(lm(uptake ~ ., data = CO2), aes(.resid)) +
      geom_histogram(bins = input$bins)
  })

  output$plotPanel1 <- renderUI({
    tagList(
      tabsetPanel(
        tabPanel(
          "plot1",
          renderPlot(plot1())
        ),
        tabPanel(
          "plot2",
          renderPlot(plot2())
        ),
        tabPanel(
          "plot3",
          renderPlot(plot3())
        )
      )
    )
  })
  output$plotPanel2 <- renderUI({
    tagList(
      fluidRow(
        column(
          4,
          renderPlot(plot1())
        ),
        column(
          4,
          renderPlot(plot2())
        ),
        column(
          4,
          renderPlot(plot3())
        )
      )
    )
  })
}

runApp(shinyApp(ui, server))


问:
php  how to pass value to another page when click the href? and how to retrieve the value from another page?
How do I pass the value with a href when click href link and go next page? Beside that, on the next page how I retrieve the value?

My code:

```<code>                <?php

            $sql = "SELECT DISTINCT movie.image, movie.name, movie.id
                                FROM movie
                                INNER JOIN movie_genre
                                ON movie.id = movie_genre.movie_id
                                INNER JOIN genre ON genre.id = movie_genre.genre_id
                                INNER JOIN movie_date ON movie_date.movie_id = movie.id
                                ORDER BY timestamp DESC LIMIT 6";

            $res = mysqli_query($conn, $sql);
            if(mysqli_num_rows($res) > 0) {
                while($row = mysqli_fetch_object($res)) {
                    echo '<label class="label1">' . $row->name . '</label><br><br>';
                    echo '<a href="#"><img src="' . $row->image . '" class="poster"></a>';
                    echo '<div class = "section3"><a href="synopsis.php?id="' . $row->id . '" >asd</a>&nbsp &nbsp <a href="">Buy Now</a>';
                }
            }

            ?>
</code>```

答:
Assuming your id is an integer.

```<code><?php

$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
</code>```

If you have a query parameter of id, the above will filter and convert the input string into an integer.  If it doesn't look like one it will assign false to $id.

Note if no value is passed $id will be null.  So in further code you may need to additionally test:

```<code><?php
if(is_int($id)) {
    // Do something.
}
</code>```

Title: php <a href> how to pass value to another page when click the href? and how to retrieve the value from another page?

Body:
How do I pass the value with a href when click href link and go next page? Beside that, on the next page how I retrieve the value?

My code:

                <?php

            $sql = "SELECT DISTINCT movie.image, movie.name, movie.id
                                FROM movie
                                INNER JOIN movie_genre
                                ON movie.id = movie_genre.movie_id
                                INNER JOIN genre ON genre.id = movie_genre.genre_id
                                INNER JOIN movie_date ON movie_date.movie_id = movie.id
                                ORDER BY timestamp DESC LIMIT 6";

            $res = mysqli_query($conn, $sql);
            if(mysqli_num_rows($res) > 0) {
                while($row = mysqli_fetch_object($res)) {
                    echo '' . $row->name . '

';
                    echo 'image . '" class="poster">';
                    echo '
id . '" >asd&nbsp &nbsp Buy Now';
                }
            }

            ?>

Body:
Assuming your id is an integer.

<?php

$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);

If you have a query parameter of id, the above will filter and convert the input string into an integer.  If it doesn't look like one it will assign false to $id.

Note if no value is passed $id will be null.  So in further code you may need to additionally test:

<?php
if(is_int($id)) {
    // Do something.
}


问:
Not logging in with requests.session()
I used requests library to log in to a website. I tried with scrapy, it is working fine. but when i try with requests, it is not working. I am getting the content of main page but not the page after logging in. when i print the url after post() method, i am not getting correct url. The code is below

```<code>    import requests
from bs4 import BeautifulSoup
r=requests.get("http://collegekart.in/login")
c=r.content
soup=BeautifulSoup(c,"html.parser")
token=soup.find("meta",{"name":"csrf-token"})
print(token)
tok=token['content']
print(tok)
s=requests.session()
login={"username":'fdgdgfdgdfgdfg@gmail.com',"password":'dgfdgdfgfdgdfgd',"csrf-token":tok}
s.post("http://collegekart.in/login",data=login)
t=s.get("http://collegekart.in/users")
print(t.url)
sop=BeautifulSoup(t.content,"html.parser")
print(sop.prettify())
</code>```

I am getting the output content of "collegekart.in" instead of "collegekart.in/users.

答: U can simply use get() method. In that use params attribute for login credentials.</p>

Title: Not logging in with requests.session()

Body:
I used requests library to log in to a website. I tried with scrapy, it is working fine. but when i try with requests, it is not working. I am getting the content of main page but not the page after logging in. when i print the url after post() method, i am not getting correct url. The code is below

    import requests
from bs4 import BeautifulSoup
r=requests.get("http://collegekart.in/login")
c=r.content
soup=BeautifulSoup(c,"html.parser")
token=soup.find("meta",{"name":"csrf-token"})
print(token)
tok=token['content']
print(tok)
s=requests.session()
login={"username":'fdgdgfdgdfgdfg@gmail.com',"password":'dgfdgdfgfdgdfgd',"csrf-token":tok}
s.post("http://collegekart.in/login",data=login)
t=s.get("http://collegekart.in/users")
print(t.url)
sop=BeautifulSoup(t.content,"html.parser")
print(sop.prettify())

I am getting the output content of "collegekart.in" instead of "collegekart.in/users.


问:
Eliminate possibility of belated data manipulations on MySQL table
I want to guarantee that the rows in my MySQL table cannot be manipulated after their creation.

I know that only granting insert and select privileges is one step in this direction, but I also want to make sure the root user cannot alter data after insertion.

Incremental hashing:
To this end, I think about an additional column 'hash', that stores the hash value of the last row's hash concatted with the new column data.

If I then export the hashes eg. every day, any manipulation could be detected.

Am I right? Can you point me to some resources where this has been done already? Would one do this with a trigger? Maybe even in an auxiliary table that is only accessible by root?

答:
Something like that :</p>

```<code>DELIMITER $$
CREATE TRIGGER trigger_hash
AFTER INSERT
   ON table_name FOR EACH ROW

BEGIN
UPDATE table_name
SET hash = MD5(concat(NEW.field1, NEW.field2, NEW.field3, ...))
WHERE id= NEW.id
END;
$$
DELIMITER ;
</code>```

Body:
Something like that :

DELIMITER $$
CREATE TRIGGER trigger_hash
AFTER INSERT
   ON table_name FOR EACH ROW

BEGIN
UPDATE table_name
SET hash = MD5(concat(NEW.field1, NEW.field2, NEW.field3, ...))
WHERE id= NEW.id
END;
$$
DELIMITER ;


问:
ios UITextField to edit with uidatepicker
I have a uitextfield where is written a date.. how can I show on the bottom of the page a uidatepicker instead of a standard keyboard?
thanks in advance</p>

答:
Make sure your class implements the UITextFieldDelegate protocol. Then, override the shouldBeginEditing delegate method to return FALSE:

```<code>- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    //check if it is the UITextField you don't want the keyboard for
    if (textField != dateTextField)
        return TRUE;

    //present your UIDatePicker
    //see instructions below

    //Return false to prevent the keyboard from appearing.
    return FALSE;
}
</code>```

I recommend using another UIViewController that contains a UIDatePicker and use presentModalViewController to show it. This conforms to the User-Interface Guidelines.

Body:
Make sure your class implements the UITextFieldDelegate protocol. Then, override the shouldBeginEditing delegate method to return FALSE:

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    //check if it is the UITextField you don't want the keyboard for
    if (textField != dateTextField)
        return TRUE;

    //present your UIDatePicker
    //see instructions below

    //Return false to prevent the keyboard from appearing.
    return FALSE;
}

I recommend using another UIViewController that contains a UIDatePicker and use presentModalViewController to show it. This conforms to the User-Interface Guidelines.


问:
Can thrift server side detect "invalid method name" calling?
The question is, the thrift client side throws exception: org.apache.thrift.TApplicationException: Invalid method name: 'xxxNotMyMethod', while the server side cannot detect what is happening.

Is there a way to logging this situation on server just like "HTTP 404 Not Found" on Nginx's error.log?

答:
No, since inside the process() method the method names are just looked up against a compiler-generated key-value dictionary or map to find the implementation. If that fails, the code throws an TApplicationException.

If you have the chance to wrap the processor call (e.g. override process()) into some other code, then you could theoretically catch that exception and do some additional things.


问:
T-SQL with three sub queries causing long execution time, any combination of 2 is near instant
I have the following T-SQL:

```<code>SELECT TOP (1) *, (
    SELECT COUNT(result_id)
    FROM Result
    JOIN TestRun ON (TestRun.test_run_id = Result.test_run_id)
    JOIN RegressionRun ON (RegressionRun.regression_run_id = TestRun.regression_run_id)
    WHERE RegressionRun.regression_run_id = RR.regression_run_id AND result_type_id = 31
)  a, (
    SELECT COUNT(result_id)
    FROM Result
    JOIN TestRun ON (TestRun.test_run_id = Result.test_run_id)
    JOIN RegressionRun ON (RegressionRun.regression_run_id = TestRun.regression_run_id)
    WHERE RegressionRun.regression_run_id = RR.regression_run_id AND result_type_id = 32
)  b, (
    SELECT COUNT(result_id)
    FROM Result
    JOIN TestRun ON (TestRun.test_run_id = Result.test_run_id)
    JOIN RegressionRun ON (RegressionRun.regression_run_id = TestRun.regression_run_id)
    WHERE RegressionRun.regression_run_id = RR.regression_run_id AND result_type_id = 33
)  c
FROM RegressionRun RR
ORDER BY regression_run_id DESC
</code>```

Columns a, b and c are executing almost identical sub queries, the only difference being the result_type_id comparison in the WHERE clause.

If I run this query it takes ~10 seconds to complete.

If I remove any one of the sub query columns (a, b or c) it takes a few milliseconds to complete.

Why is adding the third sub query causing such a significant increase in performance?

Other possibly useful information:

The RegressionRun table has ~300 rows, TestRun has ~600 rows and Result has ~5 million rows

Issue is 100% reproducible

The SQL Server has plenty of spare resource and nothing else is using it when I am executing these queries

Using SQL Server 2017

Any suggestions as to why this may be occurring and how to resolve it would be greatly appreciated.

答:
I don't know why the performance is varying so greatly based on the number of correlated subqueries you include.  But we should pause for a moment and ask why you even need correlated subqueries.  We can try to rephrase your query using direct joins with conditional aggregation:</p>

```<code>SELECT
    t1.*, t2.a, t2.b, t2.c
FROM RegressionRun t1
INNER JOIN
(
    SELECT
        rr.regression_run_id,
        SUM(CASE WHEN result_type_id = 31 THEN 1 ELSE 0 END) AS a,
        SUM(CASE WHEN result_type_id = 32 THEN 1 ELSE 0 END) AS b,
        SUM(CASE WHEN result_type_id = 33 THEN 1 ELSE 0 END) AS c
    FROM RegressionRun rr
    INNER JOIN TestRun tr
        ON rr.regression_run_id = tr.regression_run_id
    INNER JOIN Result r
        ON tr.test_run_id = r.test_run_id
    GROUP BY
        rr.regression_run_id
) t2
    ON t1.regression_run_id = t2.regression_run_id;
</code>```

Body:
I have the following T-SQL:

SELECT TOP (1) *, (
    SELECT COUNT(result_id)
    FROM Result
    JOIN TestRun ON (TestRun.test_run_id = Result.test_run_id)
    JOIN RegressionRun ON (RegressionRun.regression_run_id = TestRun.regression_run_id)
    WHERE RegressionRun.regression_run_id = RR.regression_run_id AND result_type_id = 31
)  a, (
    SELECT COUNT(result_id)
    FROM Result
    JOIN TestRun ON (TestRun.test_run_id = Result.test_run_id)
    JOIN RegressionRun ON (RegressionRun.regression_run_id = TestRun.regression_run_id)
    WHERE RegressionRun.regression_run_id = RR.regression_run_id AND result_type_id = 32
)  b, (
    SELECT COUNT(result_id)
    FROM Result
    JOIN TestRun ON (TestRun.test_run_id = Result.test_run_id)
    JOIN RegressionRun ON (RegressionRun.regression_run_id = TestRun.regression_run_id)
    WHERE RegressionRun.regression_run_id = RR.regression_run_id AND result_type_id = 33
)  c
FROM RegressionRun RR
ORDER BY regression_run_id DESC

Columns a, b and c are executing almost identical sub queries, the only difference being the result_type_id comparison in the WHERE clause.

If I run this query it takes ~10 seconds to complete.

If I remove any one of the sub query columns (a, b or c) it takes a few milliseconds to complete.

Why is adding the third sub query causing such a significant increase in performance?

Other possibly useful information:

The RegressionRun table has ~300 rows, TestRun has ~600 rows and Result has ~5 million rows

Issue is 100% reproducible

The SQL Server has plenty of spare resource and nothing else is using it when I am executing these queries

Using SQL Server 2017

Any suggestions as to why this may be occurring and how to resolve it would be greatly appreciated.

Body:
I don't know why the performance is varying so greatly based on the number of correlated subqueries you include.  But we should pause for a moment and ask why you even need correlated subqueries.  We can try to rephrase your query using direct joins with conditional aggregation:

SELECT
    t1.*, t2.a, t2.b, t2.c
FROM RegressionRun t1
INNER JOIN
(
    SELECT
        rr.regression_run_id,
        SUM(CASE WHEN result_type_id = 31 THEN 1 ELSE 0 END) AS a,
        SUM(CASE WHEN result_type_id = 32 THEN 1 ELSE 0 END) AS b,
        SUM(CASE WHEN result_type_id = 33 THEN 1 ELSE 0 END) AS c
    FROM RegressionRun rr
    INNER JOIN TestRun tr
        ON rr.regression_run_id = tr.regression_run_id
    INNER JOIN Result r
        ON tr.test_run_id = r.test_run_id
    GROUP BY
        rr.regression_run_id
) t2
    ON t1.regression_run_id = t2.regression_run_id;


问:
docker bridging localhost port
There is a chatbot-service running on my local machine at Port 50160. This port is for receiving messages from my nodejs-service in the docker container. To send messages to the chat-service the docker-container has port 8080open. This works fine.

I start it using docker run -p 8080:8080  registry.gitlab.com/abc/def/adapter-xyz.

But sending a response from the docker-container to the chatbot returns the following error in the docker container:

```<code>ChatConnector: message received.
Error: connect ECONNREFUSED 127.0.0.1:50160
    at Object.exports._errnoException (util.js:1020:11)
    at exports._exceptionWithHostPort (util.js:1043:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1086:14)
</code>```

It seems that it cannot send back a response to chatbot (running on my machine). Any idea?

答:
You should use the IP address of the host instead of 127.0.0.1. The address can be easily extracted by executing:

```<code>docker network inspect -f '{{ range .IPAM.Config }}{{.Gateway}}{{end}}' bridge
</code>```

I read in the comments that you can't change that address (btw, hardcoding is never a good idea). Another solution would be to add a iptables rule in the container itself to redirect the inbound traffic to port 50160 to the host machine. I'm not very fond of this idea since it's pretty hacky but it should work.

Title: docker bridging localhost port

Body:
There is a chatbot-service running on my local machine at Port 50160. This port is for receiving messages from my nodejs-service in the docker container. To send messages to the chat-service the docker-container has port 8080open. This works fine.

I start it using docker run -p 8080:8080  registry.gitlab.com/abc/def/adapter-xyz.

But sending a response from the docker-container to the chatbot returns the following error in the docker container:

ChatConnector: message received.
Error: connect ECONNREFUSED 127.0.0.1:50160
    at Object.exports._errnoException (util.js:1020:11)
    at exports._exceptionWithHostPort (util.js:1043:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1086:14)

It seems that it cannot send back a response to chatbot (running on my machine). Any idea?

Body:
You should use the IP address of the host instead of 127.0.0.1. The address can be easily extracted by executing:

docker network inspect -f '{{ range .IPAM.Config }}{{.Gateway}}{{end}}' bridge

I read in the comments that you can't change that address (btw, hardcoding is never a good idea). Another solution would be to add a iptables rule in the container itself to redirect the inbound traffic to port 50160 to the host machine. I'm not very fond of this idea since it's pretty hacky but it should work.


问:
Thymeleaf Template Engine Bean ignored
I have a Spring Application, but my Config for Thymeleaf is completely ignored. What am I doing wrong? I need Thymeleaf to process external Javascript files, but without a working Config I cant add a Javascript Templateresolver.

I know that its not working because Thymeleaf tells me that HTML5 mode is deprecated, but as you can see I set the mode to HTML.

```<code>package de.xy;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
@EntityScan("de.xy.model")
public class Application extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }
}
</code>```

Config

```<code>package de.xy.config;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.extras.springsecurity4.dialect.SpringSecurityDialect;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ITemplateResolver;

@Configuration
@EnableWebMvc
@ComponentScan("de.xy")
public class ThymeleafConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Bean
    public ViewResolver viewResolver() {
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(templateEngine());
        resolver.setCharacterEncoding("UTF-8");
        return resolver;
    }

    @Bean
    public TemplateEngine templateEngine() {
        SpringTemplateEngine engine = new SpringTemplateEngine();
        engine.setEnableSpringELCompiler(true);
        engine.setTemplateResolver(templateResolver());
        engine.addDialect(new SpringSecurityDialect());
        return engine;
    }

    private ITemplateResolver templateResolver() {
        SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
        resolver.setApplicationContext(applicationContext);
        resolver.setPrefix("/WEB-INF/templates/");
        resolver.setTemplateMode(TemplateMode.HTML);
        return resolver;
    }
}
</code>```

EDIT:

Working Config:

```<code>@Configuration
public class ThymeleafConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware {

    private static final String UTF8    = "UTF-8";

    private ApplicationContext  applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Bean
    public ViewResolver htmlViewResolver() {
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(templateEngine(htmlTemplateResolver()));
        resolver.setContentType("text/html");
        resolver.setCharacterEncoding(UTF8);
        resolver.setViewNames(new String[] { "*.html" });
        return resolver;
    }

    @Bean
    public ViewResolver cssViewResolver() {
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(templateEngine(cssTemplateResolver()));
        resolver.setContentType("text/css");
        resolver.setCharacterEncoding(UTF8);
        resolver.setViewNames(new String[] { "*.css" });
        return resolver;
    }

    @Bean
    public ViewResolver javascriptViewResolver() {
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(templateEngine(javascriptTemplateResolver()));
        resolver.setContentType("application/javascript");
        resolver.setCharacterEncoding(UTF8);
        resolver.setViewNames(new String[] { "*.js" });
        return resolver;
    }

    private TemplateEngine templateEngine(ITemplateResolver templateResolver) {
        SpringTemplateEngine engine = new SpringTemplateEngine();
        engine.setTemplateResolver(templateResolver);
        return engine;
    }

    private ITemplateResolver htmlTemplateResolver() {
        SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
        resolver.setApplicationContext(applicationContext);
        resolver.setPrefix("/WEB-INF/templates/");
        resolver.setTemplateMode(TemplateMode.HTML);
        return resolver;
    }

    private ITemplateResolver cssTemplateResolver() {
        SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
        resolver.setApplicationContext(applicationContext);
        resolver.setPrefix("/WEB-INF/css/");
        resolver.setTemplateMode(TemplateMode.CSS);
        return resolver;
    }

    private ITemplateResolver javascriptTemplateResolver() {
        SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
        resolver.setApplicationContext(applicationContext);
        resolver.setPrefix("/WEB-INF/js/");
        resolver.setTemplateMode(TemplateMode.JAVASCRIPT);
        return resolver;
    }
}
</code>```

JavascriptController:

```<code>@Controller
@RequestMapping("js")
public class JavascriptController {

    @RequestMapping("somejavascriptfile.js")
    public String getJS() {
        return "somejavascriptfile.js";
    }}
</code>```

It is more than I need, but it works (Controller does nothing)

答:
I usually register my static contents like this :

```<code>@Override
protected void addResourceHandlers( ResourceHandlerRegistry registry ) {
    registry.addResourceHandler( "/js/**", "/css/**", "/images/**" ).addResourceLocations( "classpath:static/js/", "classpath:static/css/", "classpath:static/images/" );
}
</code>```

You do not need to define again a new controller.

EDIT

And in Thymeleaf, example to include css files :

```<code><link rel="stylesheet" th:href="@{css/styles.css}" />
</code>```

Title: Thymeleaf Template Engine Bean ignored

Body:
I have a Spring Application, but my Config for Thymeleaf is completely ignored. What am I doing wrong? I need Thymeleaf to process external Javascript files, but without a working Config I cant add a Javascript Templateresolver.

I know that its not working because Thymeleaf tells me that HTML5 mode is deprecated, but as you can see I set the mode to HTML.

package de.xy;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
@EntityScan("de.xy.model")
public class Application extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }
}

Config

package de.xy.config;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.extras.springsecurity4.dialect.SpringSecurityDialect;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ITemplateResolver;

@Configuration
@EnableWebMvc
@ComponentScan("de.xy")
public class ThymeleafConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Bean
    public ViewResolver viewResolver() {
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(templateEngine());
        resolver.setCharacterEncoding("UTF-8");
        return resolver;
    }

    @Bean
    public TemplateEngine templateEngine() {
        SpringTemplateEngine engine = new SpringTemplateEngine();
        engine.setEnableSpringELCompiler(true);
        engine.setTemplateResolver(templateResolver());
        engine.addDialect(new SpringSecurityDialect());
        return engine;
    }

    private ITemplateResolver templateResolver() {
        SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
        resolver.setApplicationContext(applicationContext);
        resolver.setPrefix("/WEB-INF/templates/");
        resolver.setTemplateMode(TemplateMode.HTML);
        return resolver;
    }
}

EDIT:

Working Config:

@Configuration
public class ThymeleafConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware {

    private static final String UTF8    = "UTF-8";

    private ApplicationContext  applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Bean
    public ViewResolver htmlViewResolver() {
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(templateEngine(htmlTemplateResolver()));
        resolver.setContentType("text/html");
        resolver.setCharacterEncoding(UTF8);
        resolver.setViewNames(new String[] { "*.html" });
        return resolver;
    }

    @Bean
    public ViewResolver cssViewResolver() {
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(templateEngine(cssTemplateResolver()));
        resolver.setContentType("text/css");
        resolver.setCharacterEncoding(UTF8);
        resolver.setViewNames(new String[] { "*.css" });
        return resolver;
    }

    @Bean
    public ViewResolver javascriptViewResolver() {
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(templateEngine(javascriptTemplateResolver()));
        resolver.setContentType("application/javascript");
        resolver.setCharacterEncoding(UTF8);
        resolver.setViewNames(new String[] { "*.js" });
        return resolver;
    }

    private TemplateEngine templateEngine(ITemplateResolver templateResolver) {
        SpringTemplateEngine engine = new SpringTemplateEngine();
        engine.setTemplateResolver(templateResolver);
        return engine;
    }

    private ITemplateResolver htmlTemplateResolver() {
        SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
        resolver.setApplicationContext(applicationContext);
        resolver.setPrefix("/WEB-INF/templates/");
        resolver.setTemplateMode(TemplateMode.HTML);
        return resolver;
    }

    private ITemplateResolver cssTemplateResolver() {
        SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
        resolver.setApplicationContext(applicationContext);
        resolver.setPrefix("/WEB-INF/css/");
        resolver.setTemplateMode(TemplateMode.CSS);
        return resolver;
    }

    private ITemplateResolver javascriptTemplateResolver() {
        SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
        resolver.setApplicationContext(applicationContext);
        resolver.setPrefix("/WEB-INF/js/");
        resolver.setTemplateMode(TemplateMode.JAVASCRIPT);
        return resolver;
    }
}

JavascriptController:

@Controller
@RequestMapping("js")
public class JavascriptController {

    @RequestMapping("somejavascriptfile.js")
    public String getJS() {
        return "somejavascriptfile.js";
    }}

It is more than I need, but it works (Controller does nothing)

Body:
I usually register my static contents like this :

@Override
protected void addResourceHandlers( ResourceHandlerRegistry registry ) {
    registry.addResourceHandler( "/js/**", "/css/**", "/images/**" ).addResourceLocations( "classpath:static/js/", "classpath:static/css/", "classpath:static/images/" );
}

You do not need to define again a new controller.

EDIT

And in Thymeleaf, example to include css files :

<link rel="stylesheet" th:href="@{css/styles.css}" />


问:
How to allow tab on a custom control in HTML/Javascript (Aurelia)
I have created a custom control in Aurelia which is just a visual made up of divs (no actual input controls). When I tab through my form I would like to call a function to do stuff when the tab lands on my custom control, but it does not land on it as it is not an input. How do I get the tab to land on my custom control?

This will also apply for Angular and HTML in general.

答:
If you wish for a user to tab onto something, you should at first look into using other elements than div's for said element (maybe a button?).

However, if you do need to use a div you can add tabindex="0" to it:

```<code><div class="custom-control" tabindex="0"></div>
</code>```

More info on the tabindex attribute here

Body:
If you wish for a user to tab onto something, you should at first look into using other elements than div's for said element (maybe a button?).

However, if you do need to use a div you can add tabindex="0" to it:

<div class="custom-control" tabindex="0"></div>

More info on the tabindex attribute here


问:
Angular 2 multiple components declaration
I'm working on a generic Ionic 2 app which consist in loading and displaying multiple components on the first page.

Each add-ons need to be easily created and implemented in the app very easily. So I created a file named "addon-declaration.ts". Inside this file, I exported all my components :

```<code>export { MyFirstAddon } from './components/addon1/first.addon';
export { MySecondAddon } from './components/addon2/second.addon';
export { MyThirdAddon } from './components/addon3/third.addon';
</code>```

So my question is how to import all my components directly on "app.module.ts" declarations field ?

I already tried this but it's not working :/

```<code>import * as ModuleHandler from '../models/addons/addon-declaration';

@NgModule({
  declarations: [
    MyApp,
    ModuleHandler <--- Not working
  ],
  imports: [
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp
  ],
  providers: [{provide: ErrorHandler, useClass: IonicErrorHandler}]
})
export class AppModule {}
</code>```

It's working nice if I import them one by one :

```<code>import { MyFirstAddon } from'../components/addon1/first.addon';
import { MySecondAddon } from'../components/addon2/second.addon';
import { MyThirdAddon } from'../components/addon3/third.addon';

@NgModule({
      declarations: [
        MyApp,
        MyFirstAddon, <--- Working well
        MySecondAddon,
        MyThirdAddon
      ],
</code>```

答:
Create a index.ts inside that folder where your all addon files are placed and then export all files like :

```<code>export * from './first.addon';
export * from './second.addon';
export * from './third.addon';
.....
</code>```

then after you need to import all the addons files in your app.module.ts like :

```<code>import * as allAddons from './addons_files';
</code>```

at the end you need to use allAddons object like :

```<code>@NgModule({
    declarations: [
      // all-addons
      allAddons.FirstAddon,
      allAddons.SecondAddon,
      allAddons.ThirdAddon
    ]
})
export class AppModule() {
}
</code>```

Body:
I'm working on a generic Ionic 2 app which consist in loading and displaying multiple components on the first page.

Each add-ons need to be easily created and implemented in the app very easily. So I created a file named "addon-declaration.ts". Inside this file, I exported all my components :

export { MyFirstAddon } from './components/addon1/first.addon';
export { MySecondAddon } from './components/addon2/second.addon';
export { MyThirdAddon } from './components/addon3/third.addon';

So my question is how to import all my components directly on "app.module.ts" declarations field ?

I already tried this but it's not working :/

import * as ModuleHandler from '../models/addons/addon-declaration';

@NgModule({
  declarations: [
    MyApp,
    ModuleHandler <--- Not working
  ],
  imports: [
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp
  ],
  providers: [{provide: ErrorHandler, useClass: IonicErrorHandler}]
})
export class AppModule {}

It's working nice if I import them one by one :

import { MyFirstAddon } from'../components/addon1/first.addon';
import { MySecondAddon } from'../components/addon2/second.addon';
import { MyThirdAddon } from'../components/addon3/third.addon';

@NgModule({
      declarations: [
        MyApp,
        MyFirstAddon, <--- Working well
        MySecondAddon,
        MyThirdAddon
      ],

Body:
Create a index.ts inside that folder where your all addon files are placed and then export all files like :

export * from './first.addon';
export * from './second.addon';
export * from './third.addon';
.....

then after you need to import all the addons files in your app.module.ts like :

import * as allAddons from './addons_files';

at the end you need to use allAddons object like :

@NgModule({
    declarations: [
      // all-addons
      allAddons.FirstAddon,
      allAddons.SecondAddon,
      allAddons.ThirdAddon
    ]
})
export class AppModule() {
}


问:
Why does a Fortran POINTER require a TARGET?
Why does the Fortran 90 Specification specify (5.2.8) that the TARGET keyword must be used to associate a POINTER to it? Why isn't every type a valid TARGET?

For example,
```
INTEGER, POINTER :: px
INTEGER, TARGET :: x
x = 5
px => x
```
is valid syntax but
```
INTEGER, POINTER :: px
INTEGER :: x
x = 5
px => x
```
is not valid.

Why must this be?

答: An item that might be pointed to could be aliased to another item, and the compiler must allow for this.   Items without the target attribute should not be aliased and the compiler can make assumptions based on this and therefore produce more efficient code.</p>

Body:
Why does the Fortran 90 Specification specify (5.2.8) that the TARGET keyword must be used to associate a POINTER to it? Why isn't every type a valid TARGET?

For example,

INTEGER, POINTER :: px
INTEGER, TARGET :: x
x = 5
px => x

is valid syntax but

INTEGER, POINTER :: px
INTEGER :: x
x = 5
px => x

is not valid.

Why must this be?


问:
Laravel Middleware return variable to controller
I am carrying out a permissions check on a user to determine whether they can view a page or not. This involves passing the request through some middleware first.

The problem I have is I am duplicating the same database query in the middleware and in the controller before returning the data to the view itself.

Here is an example of the setup;

-- routes.php

```<code>Route::get('pages/{id}', [
   'as' => 'pages',
   'middleware' => 'pageUser'
   'uses' => 'PagesController@view'
]);
</code>```

-- PageUserMiddleware.php (class PageUserMiddleware)

```<code>public function handle($request, Closure $next)
    {
        //get the page
        $pageId = $request->route('id');
        //find the page with users
        $page = Page::with('users')->where('id', $pageId)->first();
        //check if the logged in user exists for the page
        if(!$page->users()->wherePivot('user_id', Auth::user()->id)->exists()) {
            //redirect them if they don't exist
            return redirect()->route('redirectRoute');
        }
        return $next($request);
    }
</code>```

-- PagesController.php

```<code>public function view($id)
{
    $page = Page::with('users')->where('id', $id)->first();
    return view('pages.view', ['page' => $page]);
}
</code>```

As you can see, the Page::with('users')->where('id', $id)->first() is repeated in both the middleware and controller. I need to pass the data through from one to the other so an not to duplicate.

答:
$request is the array so that we can just add value and key to the array and get the $request with this key in the controller.

$request['id'] = $id;

Body:
I am carrying out a permissions check on a user to determine whether they can view a page or not. This involves passing the request through some middleware first.

The problem I have is I am duplicating the same database query in the middleware and in the controller before returning the data to the view itself.

Here is an example of the setup;

-- routes.php

Route::get('pages/{id}', [
   'as' => 'pages',
   'middleware' => 'pageUser'
   'uses' => 'PagesController@view'
]);

-- PageUserMiddleware.php (class PageUserMiddleware)

public function handle($request, Closure $next)
    {
        //get the page
        $pageId = $request->route('id');
        //find the page with users
        $page = Page::with('users')->where('id', $pageId)->first();
        //check if the logged in user exists for the page
        if(!$page->users()->wherePivot('user_id', Auth::user()->id)->exists()) {
            //redirect them if they don't exist
            return redirect()->route('redirectRoute');
        }
        return $next($request);
    }

-- PagesController.php

public function view($id)
{
    $page = Page::with('users')->where('id', $id)->first();
    return view('pages.view', ['page' => $page]);
}

As you can see, the Page::with('users')->where('id', $id)->first() is repeated in both the middleware and controller. I need to pass the data through from one to the other so an not to duplicate.


问:
Connections Not Being Closed SQLAlchemy
I have recently been seeing MySQL server has gone away in my application logs for a daemon that I have running utilizing SQLAlchemy.

I wrap every database query or update in a decorator that should close all the sessions after finishing. In theory, that should also close the connection.

My decorator looks like

```<code>  def dbop(meth):
    @wraps(meth)
    def nf(self, *args, **kwargs):
      self.session = self.sm()
      res = meth(self, *args, **kwargs)
      self.session.commit()
      self.session.close()
      return res
    return nf
</code>```

I also initialize the database at the top of my Python script with:

```<code>  def initdb(self):
    engine = create_engine(db_url)
    Base.metadata.create_all(engine)
    self.sm = sessionmaker(bind=engine,
                           autocommit=False,
                           autoflush=False,
                           expire_on_commit=False)
</code>```

To my understanding, I am getting that error because my connection is timing out. Why would this be the case if I wrap each method in that decorator above? Is this because expire_on_commit cause queries even after connection is closed and might reopen them? Is this because Base.metadata.create_all causes SQL to be executed which opens a connection that isn't closed?

答:
Your session is bound to an "engine", which in turn uses a connection pool. Each time SQLAlchemy requires a connection it checks one out from the pool, and if it is done with it, it is returned to the pool but it is not closed! This is a common strategy to reduce overhead from opening/closing connections. All the options you set above have only an impact on the session, not the connection!

By default, the connections in the pool are kept open indefinitely.

But MySQL will automatically close the connection after a certain amount of inactivity (See wait_timeout).

The issue here is that your Python process will not be informed by the MySQL server that the connection was closed if it falls into the inactivity timeout. Instead, the next time a query is sent to that connection, the Python will discover that the connection is no longer available. A similar thing can happen if the connection is lost due to other reasons, for example forced service restarts which don't wait for open connections to be cleanly closed (for example, using the "immediate" option in postgres restarts).

This is when you run into the exception.

SQLAlchemy gives you various strategies of dealing with this, which are well documented int the "Dealing with Disconnects" section as mentioned by @lukas-graf

If you jump through some hoops you can get a reference to the connection which is currently in use by the session. You could close it that way but I strongly recommend against this. Instead, refer to the "Dealing with Disconnects" session above, and let SQLAlchemy deal with this for you transparently. In your case, setting the pool_recycle option might solve your problem.

Title: Connections Not Being Closed SQLAlchemy

Body:
I have recently been seeing MySQL server has gone away in my application logs for a daemon that I have running utilizing SQLAlchemy.

I wrap every database query or update in a decorator that should close all the sessions after finishing. In theory, that should also close the connection.

My decorator looks like

  def dbop(meth):
    @wraps(meth)
    def nf(self, *args, **kwargs):
      self.session = self.sm()
      res = meth(self, *args, **kwargs)
      self.session.commit()
      self.session.close()
      return res
    return nf

I also initialize the database at the top of my Python script with:

  def initdb(self):
    engine = create_engine(db_url)
    Base.metadata.create_all(engine)
    self.sm = sessionmaker(bind=engine,
                           autocommit=False,
                           autoflush=False,
                           expire_on_commit=False)

To my understanding, I am getting that error because my connection is timing out. Why would this be the case if I wrap each method in that decorator above? Is this because expire_on_commit cause queries even after connection is closed and might reopen them? Is this because Base.metadata.create_all causes SQL to be executed which opens a connection that isn't closed?


问:
How to hide keyboard in swift on pressing return key?
I am using UITextfied while clicking on textfied keyboard appear but when i pressed the return key, keyboard is not disappearing. I used the following code:

```<code>func textFieldShouldReturn(textField: UITextField!) -> Bool // called when 'return' key pressed. return NO to ignore.
{
    return true;
}
</code>```

the method resignfirstresponder is not getting in function.

答:
Swift

Using optional function from UITextFieldDelegate.

```<code>func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.endEditing(false)
}
</code>```

false means that field can be ask to resign. true – force resign.

Body:
I am using UITextfied while clicking on textfied keyboard appear but when i pressed the return key, keyboard is not disappearing. I used the following code:

func textFieldShouldReturn(textField: UITextField!) -> Bool // called when 'return' key pressed. return NO to ignore.
{
    return true;
}

the method resignfirstresponder is not getting in function.

Body:
Swift

Using optional function from UITextFieldDelegate.

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.endEditing(false)
}

false means that field can be ask to resign. true – force resign.


问:
How to generate unique ids for RecyclerView, in case of 2 ids per item?

Background

Suppose I have a RecyclerView, which has items that can only be unique if you look at 2 ids they have, but not just one of them.

The first Id is the primary one. Usually there aren't 2 items that have the same primary ID, but sometimes it might occur, which is why there is a secondary ID.

In my

The problem

The RecyclerView adapter needs to have a "long" type being returned:

https://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html#getItemId(int)

What I've tried

The easy way to overcome this, is to have a HashMap and a counter.

The HashMap will contain the combined-keys, and the value will be the id that should be returned. The counter is used to generated the next id in case of a new combined key. The combined key can be a "Pair" class in this case.

Suppose each item in the RecyclerView data has 2 long-type keys:

```<code>HashMap<Pair<Long,Long>,Long> keyToIdMap=new HashMap();
long idGenerator=0;
</code>```

this is what to do in getItemId :

```<code>Pair<Long,Long> combinedKey=new Pair(item.getPrimaryId(), item.getSecondary());
Long uniqueId=keyToIdMap.get(combinedKey);
if(uniqueId==null)
  keyToIdMap.put(combinedKey,uniqueId=idGenerator++);
return uniqueId;
</code>```

This has the drawback of taking more and more memory. Not much though, and it's very small and proportional to the data you already have, but still...

However, this has the advantage of being able to handle all types of IDs, and you can use even more IDs as you wish (just need something similar to Pair).

Another advantage is that it will use all IDs starting from 0.

The question

Is there perhaps a better way to achieve this?

Maybe a mathematical way? I remember I learned in the past of using prime numbers for similar tasks. Will it work here somehow?

答:
I think my original idea is the best one I can think of.
Should cover all possible ids, with least possible collision. </p>

Body:
Background

Suppose I have a RecyclerView, which has items that can only be unique if you look at 2 ids they have, but not just one of them.

The first Id is the primary one. Usually there aren't 2 items that have the same primary ID, but sometimes it might occur, which is why there is a secondary ID.

In my

The problem

The RecyclerView adapter needs to have a "long" type being returned:

https://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html#getItemId(int)

What I've tried

The easy way to overcome this, is to have a HashMap and a counter.

The HashMap will contain the combined-keys, and the value will be the id that should be returned. The counter is used to generated the next id in case of a new combined key. The combined key can be a "Pair" class in this case.

Suppose each item in the RecyclerView data has 2 long-type keys:

HashMap<Pair<Long,Long>,Long> keyToIdMap=new HashMap();
long idGenerator=0;

this is what to do in getItemId :

Pair<Long,Long> combinedKey=new Pair(item.getPrimaryId(), item.getSecondary());
Long uniqueId=keyToIdMap.get(combinedKey);
if(uniqueId==null)
  keyToIdMap.put(combinedKey,uniqueId=idGenerator++);
return uniqueId;

This has the drawback of taking more and more memory. Not much though, and it's very small and proportional to the data you already have, but still...

However, this has the advantage of being able to handle all types of IDs, and you can use even more IDs as you wish (just need something similar to Pair).

Another advantage is that it will use all IDs starting from 0.

The question

Is there perhaps a better way to achieve this?

Maybe a mathematical way? I remember I learned in the past of using prime numbers for similar tasks. Will it work here somehow?


问:
Sort an array in the same order of another array
I have a few arrays of 50+ names like this.

```<code>["dan", "ryan", "bob", "steven", "corbin"]
["bob", "dan", "steven", "corbin"]
</code>```

I have another array that has the correct order. Note that the second array above does not include all of the names, but I still want it to follow the order of the following:

```<code>["ryan", "corbin", "dan", "steven", "bob"]
</code>```

There is no logical order to it, they are just in this order. What makes sense to me is to compare each array against the correctly ordered one. I think I saw some people doing this with PHP, but I was not able to find a JavaScript solution. Does anyone have any idea how to do this? I've been trying for a few hours and I'm stumped.

答:
If you need to place values of your array in the recurring order, meaning:

Input: [1, 2, 4, 4, 3, 3, 2, 1]

Output: [1, 2, 3, 4, 1, 2, 3, 4]

Then you can use 2 functions below. The first one uses the second one.

For the first function you will need to provide 2 arguments:

1st argument: your array of items that should be ordered (Input from above)

2nd argument: array of the correct order ([1, 2, 3, 4] for the example above)

```<code>function sortByOrder (array, order) {

    const arrayOfArrays = order.map(v => {

        return [...Array(howMany(v, array))].map(undef => v);
    });

    const tempArray = [];

    arrayOfArrays.forEach((subArr, i) => {

        let index = order.indexOf(order[i]);

        subArr.forEach(duplicate => {

            tempArray[index] = duplicate;

            index += order.length;
        });
    });

    return tempArray.filter(v => v);
}

function howMany(value, array) {

        const regExp = new RegExp(value, 'g');

        return (array.join(' ').match(regExp) || []).length;
}
</code>```

Body:
I have a few arrays of 50+ names like this.

["dan", "ryan", "bob", "steven", "corbin"]
["bob", "dan", "steven", "corbin"]

I have another array that has the correct order. Note that the second array above does not include all of the names, but I still want it to follow the order of the following:

["ryan", "corbin", "dan", "steven", "bob"]

There is no logical order to it, they are just in this order. What makes sense to me is to compare each array against the correctly ordered one. I think I saw some people doing this with PHP, but I was not able to find a JavaScript solution. Does anyone have any idea how to do this? I've been trying for a few hours and I'm stumped.

Body:
If you need to place values of your array in the recurring order, meaning:

Input: [1, 2, 4, 4, 3, 3, 2, 1]

Output: [1, 2, 3, 4, 1, 2, 3, 4]

Then you can use 2 functions below. The first one uses the second one.

For the first function you will need to provide 2 arguments:

1st argument: your array of items that should be ordered (Input from above)

2nd argument: array of the correct order ([1, 2, 3, 4] for the example above)

function sortByOrder (array, order) {

    const arrayOfArrays = order.map(v => {

        return [...Array(howMany(v, array))].map(undef => v);
    });

    const tempArray = [];

    arrayOfArrays.forEach((subArr, i) => {

        let index = order.indexOf(order[i]);

        subArr.forEach(duplicate => {

            tempArray[index] = duplicate;

            index += order.length;
        });
    });

    return tempArray.filter(v => v);
}

function howMany(value, array) {

        const regExp = new RegExp(value, 'g');

        return (array.join(' ').match(regExp) || []).length;
}