问:
Trying to multiply by 100 or 100 each row and column in CSV using PowerShell
Here is the .txt example tab delimited file as it starts out:

```<code>CH00-03 CH00-04 CH00-06 CH00-07 CH00-08
°F  °F  °F  °F  °F
1.1120e+002  1.0040e+002     4.0208e+002     4.4312e+002     4.5428e+002
2.3378e+002  2.3810e+002     2.4386e+002     2.5376e+002     4.1126e+002
2.6726e+002  2.5970e+002     2.5790e+002     2.5880e+002     2.6294e+002
-5.8662e+003    -5.8662e+003    -5.8662e+003    -5.8662e+003    -5.8662e+003
</code>```

I am running this code to change it to a CSV removing the E+ as well:

```<code>$DataPath = 'C:\Test'
$DataName = '\*.txt'
$DataTemp = '\Tempfile.csv'
$NewData = '\Complete.csv'

$DataStream = $DataPath + $DataName
$TempStream = $Datapath + $DataTemp
$NewStream = $DataPath + $NewData
#$DataContent = $DataName

$DataContent = Get-Content -Path  "$DataStream" -Raw

$Data1 = $DataContent -replace '[E+]',''
$Data2 = $Data1 #Required as for some reason no data comes out if not passed through another variable.
ECHO $Data2 > $TempStream

IMPORT-CSV -Delimiter "`t" -Header ('Column1','Column2','Column3','Column4','Column5')  -Path $TempStream | Export-Csv $NewStream -NoType
</code>```

then I was grabbing the data from the $NewStream to multiply by 100 or 1000 depending on the last digit after removing the E+

at the moment I am trying to get the multiplication to work before choosing what to multiply by here is some trial and error failures:

test to split data and digits.

```<code>$import = get-content $NewStream
$import | select -First 3 | Set-Content $Header
$import | Select-Object -Skip 3 | Set-Content $CSVOUT
$NewImport = Get-Content $CSVOUT
</code>```

tried this was not sure if this was close or not.

```<code>$NewStream | foreach-object {$_ * 100} | Set-Content "C:\Test\Testing6.csv"
</code>```

tried this however I feel this is not able ot work with what I got for some reason

```<code>$arr = $DataContent
for($i = 0; $i -lt $arr.Length; $i++){
   $arr[$i] = $arr[$i] * 100
}
ECHO $arr > "C:\Test\Testing6.csv"
</code>```

also tried it with this

```<code>$arr = $DataContent2
for($i = 0; $i -lt $arr.Length; $i++){
   $arr[$i] = [float]$arr[$i] *= 100
ECHO $arr > "C:\Test\Testing6.csv"
}
</code>```

the $NewStream looks like this

```<code>Column1,Column2,Column3,Column4,Column5
CH00-03,CH00-04,CH00-06,CH00-07,CH00-08
°F,°F,°F,°F,°F
1.1120002,1.0040002,4.0208002,4.4312002,4.5428002
2.3378002,2.3810002,2.4386002,2.5376002,4.1126002
2.6726002,2.5970002,2.5790002,2.5880002,2.6294002
-5.8662003,-5.8662003,-5.8662003,-5.8662003,-5.8662003
</code>```

I am trying to multiply all these by 100 or 1000 based on the last number per number but simply always run into different errors no matter what I try.

I think I may have made it much harder than it needs to be please help anything would be welcome to get this working correctly.  I am open to other windows programming languages as well:)

EDIT:
Thank you Mathias, you got me the rest of what I needed to finish the script.
The "`t" did not seem to work, however as seen below I found a way to work with it.

Here is the end result that works for me:

```<code>#Setup to easily change Data Path.
$DataPath = 'C:\Test'
$DataName = '\*.txt'
$DataTemp = '\Tempfile.csv'
$NewData = '\Complete.csv'
$FinalData = '\Final.csv'

#Path Concatenation.
$DataStream = $DataPath + $DataName
$TempStream = $Datapath + $DataTemp
$NewStream = $DataPath + $NewData
$OUTCSV = $DataPath + $FinalData

#Getting Content
$DataContent1 = Get-Content -Path  "$DataStream" -Raw

#Because Get-Content does not work when introduced into IMPORT-CSV directly as a variable it needs a file changed to csv.  all other ways would give me dupe header errors.
$DataContent1 > $TempStream

#Because "`t" does not work in Convertfrom-csv or Convertto-csv.  Also because of Dupe header errors, this helps the most in eliminating them.

IMPORT-CSV -Delimiter "`t" -Header ('Column1','Column2','Column3',
'Column4','Column5','Column6','Column7','Column8','Column9','Column10',
'Column11','Column12','Column13','Column14','Column15','Column16',
'Column17','Column18','Column19','Column20','Column21','Column22',
'Column23','Column24','Column25','Column26','Column27','Column28',
'Column29','Column30')  -Path $TempStream | Export-Csv $NewStream -NoType

#Grabbing the new content.
$DataContent2 = Get-Content -Path  "$NewStream" -Raw

#This is the Scientific Notation conversion to Decimal.
$DataContent2 = [regex]::Replace($DataContent2, '(-?\d+\.\d+e\+\d+)', {param($m) $m.Value -as [double]})

#This creates the File I needed:)
$DataContent2|ConvertFrom-Csv -delimiter ","|Export-Csv -Path $OUTCSV -NoTypeInformation

#To delete the CSV files used to build the Final CSV

DEL $TempStream
DEL $NewStream
</code>```

答:
You don't need to parse these numbers manually, PowerShell supports scientific notation!

PS C:\> '4.0208e+002' -as [double]
402.08
```

<p>So all you need to do is convert to values to a numerical type! You can use the <code>Regex.Replace()</code> method to pass a scriptblock that converts numbers in scientific notation like so:</p>

<pre class="lang-bsh prettyprint-override"><code>$DataContent = Get-Content -Path  "$DataStream" -Raw

$DataContent = [regex]::Replace($DataContent, '(-?\d+\.\d+e\+\d+)', {param($m) $m.Value -as [double]})
</code>```

$DataContent will now look like this for the sample input you posted:

```<code>CH00-03 CH00-04 CH00-06 CH00-07 CH00-08
°F  °F  °F  °F  °F
111.2   100.4     402.08     443.12     454.28
233.78  238.1     243.86     253.76     411.26
267.26  259.7     257.9     258.8     262.94
-5866.2    -5866.2    -5866.2    -5866.2    -5866.2
</code>```

Now just convert from TSV to objects and export to CSV again with the default delimiter and you've got yourself the format you need:

$DataContent |ConvertFrom-Csv -Delimiter "`t" |Export-Csv -Path $OUTCSV -NoTypeInformation
```

Body:
Here is the .txt example tab delimited file as it starts out:

CH00-03 CH00-04 CH00-06 CH00-07 CH00-08
°F  °F  °F  °F  °F
1.1120e+002  1.0040e+002     4.0208e+002     4.4312e+002     4.5428e+002
2.3378e+002  2.3810e+002     2.4386e+002     2.5376e+002     4.1126e+002
2.6726e+002  2.5970e+002     2.5790e+002     2.5880e+002     2.6294e+002
-5.8662e+003    -5.8662e+003    -5.8662e+003    -5.8662e+003    -5.8662e+003

I am running this code to change it to a CSV removing the E+ as well:

$DataPath = 'C:\Test'
$DataName = '\*.txt'
$DataTemp = '\Tempfile.csv'
$NewData = '\Complete.csv'

$DataStream = $DataPath + $DataName
$TempStream = $Datapath + $DataTemp
$NewStream = $DataPath + $NewData
#$DataContent = $DataName

$DataContent = Get-Content -Path  "$DataStream" -Raw

$Data1 = $DataContent -replace '[E+]',''
$Data2 = $Data1 #Required as for some reason no data comes out if not passed through another variable.
ECHO $Data2 > $TempStream

IMPORT-CSV -Delimiter "`t" -Header ('Column1','Column2','Column3','Column4','Column5')  -Path $TempStream | Export-Csv $NewStream -NoType

then I was grabbing the data from the $NewStream to multiply by 100 or 1000 depending on the last digit after removing the E+

at the moment I am trying to get the multiplication to work before choosing what to multiply by here is some trial and error failures:

test to split data and digits.

$import = get-content $NewStream
$import | select -First 3 | Set-Content $Header
$import | Select-Object -Skip 3 | Set-Content $CSVOUT
$NewImport = Get-Content $CSVOUT

tried this was not sure if this was close or not.

$NewStream | foreach-object {$_ * 100} | Set-Content "C:\Test\Testing6.csv"

tried this however I feel this is not able ot work with what I got for some reason

$arr = $DataContent
for($i = 0; $i -lt $arr.Length; $i++){
   $arr[$i] = $arr[$i] * 100
}
ECHO $arr > "C:\Test\Testing6.csv"

also tried it with this

$arr = $DataContent2
for($i = 0; $i -lt $arr.Length; $i++){
   $arr[$i] = [float]$arr[$i] *= 100
ECHO $arr > "C:\Test\Testing6.csv"
}

the $NewStream looks like this

Column1,Column2,Column3,Column4,Column5
CH00-03,CH00-04,CH00-06,CH00-07,CH00-08
°F,°F,°F,°F,°F
1.1120002,1.0040002,4.0208002,4.4312002,4.5428002
2.3378002,2.3810002,2.4386002,2.5376002,4.1126002
2.6726002,2.5970002,2.5790002,2.5880002,2.6294002
-5.8662003,-5.8662003,-5.8662003,-5.8662003,-5.8662003

I am trying to multiply all these by 100 or 1000 based on the last number per number but simply always run into different errors no matter what I try.

I think I may have made it much harder than it needs to be please help anything would be welcome to get this working correctly.  I am open to other windows programming languages as well:)

EDIT:
Thank you Mathias, you got me the rest of what I needed to finish the script.
The "`t" did not seem to work, however as seen below I found a way to work with it.

Here is the end result that works for me:

#Setup to easily change Data Path.
$DataPath = 'C:\Test'
$DataName = '\*.txt'
$DataTemp = '\Tempfile.csv'
$NewData = '\Complete.csv'
$FinalData = '\Final.csv'

#Path Concatenation.
$DataStream = $DataPath + $DataName
$TempStream = $Datapath + $DataTemp
$NewStream = $DataPath + $NewData
$OUTCSV = $DataPath + $FinalData

#Getting Content
$DataContent1 = Get-Content -Path  "$DataStream" -Raw

#Because Get-Content does not work when introduced into IMPORT-CSV directly as a variable it needs a file changed to csv.  all other ways would give me dupe header errors.
$DataContent1 > $TempStream

#Because "`t" does not work in Convertfrom-csv or Convertto-csv.  Also because of Dupe header errors, this helps the most in eliminating them.

IMPORT-CSV -Delimiter "`t" -Header ('Column1','Column2','Column3',
'Column4','Column5','Column6','Column7','Column8','Column9','Column10',
'Column11','Column12','Column13','Column14','Column15','Column16',
'Column17','Column18','Column19','Column20','Column21','Column22',
'Column23','Column24','Column25','Column26','Column27','Column28',
'Column29','Column30')  -Path $TempStream | Export-Csv $NewStream -NoType

#Grabbing the new content.
$DataContent2 = Get-Content -Path  "$NewStream" -Raw

#This is the Scientific Notation conversion to Decimal.
$DataContent2 = [regex]::Replace($DataContent2, '(-?\d+\.\d+e\+\d+)', {param($m) $m.Value -as [double]})

#This creates the File I needed:)
$DataContent2|ConvertFrom-Csv -delimiter ","|Export-Csv -Path $OUTCSV -NoTypeInformation

#To delete the CSV files used to build the Final CSV

DEL $TempStream
DEL $NewStream

Body:
You don't need to parse these numbers manually, PowerShell supports scientific notation!

PS C:\> '4.0208e+002' -as [double]
402.08

So all you need to do is convert to values to a numerical type! You can use the Regex.Replace() method to pass a scriptblock that converts numbers in scientific notation like so:

$DataContent = Get-Content -Path  "$DataStream" -Raw

$DataContent = [regex]::Replace($DataContent, '(-?\d+\.\d+e\+\d+)', {param($m) $m.Value -as [double]})

$DataContent will now look like this for the sample input you posted:

CH00-03 CH00-04 CH00-06 CH00-07 CH00-08
°F  °F  °F  °F  °F
111.2   100.4     402.08     443.12     454.28
233.78  238.1     243.86     253.76     411.26
267.26  259.7     257.9     258.8     262.94
-5866.2    -5866.2    -5866.2    -5866.2    -5866.2

Now just convert from TSV to objects and export to CSV again with the default delimiter and you've got yourself the format you need:

$DataContent |ConvertFrom-Csv -Delimiter "`t" |Export-Csv -Path $OUTCSV -NoTypeInformation


来源: stackexchange

问:
Redirecting old permalink structure to the new one
I had a wordpress site installed in a sub folder with category/post-title permalink structure, which resulted in the following url structure

http://www.mysite.com/subfolder/category/post-title

However as I needed to move my site to the root folder and changed the permalink structure to year/month/post-title, which looks like below, users who visit my website through the links published on other websites see 404 error page as expected.

http://www.mysite.com/year/month/post-title

While doing the changes, moving wordpress to the root directory and changing permalink structure, I forgot to take into account that such problem could occur. Anyway, I made a mistake and now I'm trying to fix the problem.

I wonder is there a way to redirect the old urls to the new ones? Editing .htaccess or using a plugin or something else. The method doesn't matter at this stage. All I want is to solve the problem

Any help?
Thanks in advance.

答:
mod_rewrite is what you're looking for, if you have that kind of access to your server.

http://httpd.apache.org/docs/current/mod/mod_rewrite.html

ContentLicense: CC BY-SA 3.0


问:
Slow performance of CGImage averaging
I am trying to create an image from an average of multiple images. The way I do this is to loop through the pixel value of 2 photos, add them together and divide by two. Simple math. However, while this is working, it is extremely slow (about 23 seconds to average 2x 10MP photos on a maximum specced MacBook Pro 15" 2016, compared to very much less time using Apples CIFilter API for similar algorithms). The code I'm currently using is this, based on another StackOverflow question here:

```<code>static func averageImages(primary: CGImage, secondary: CGImage) -> CGImage? {
        guard (primary.width == secondary.width && primary.height == secondary.height) else {
            return nil
        }

        let colorSpace       = CGColorSpaceCreateDeviceRGB()
        let width            = primary.width
        let height           = primary.height
        let bytesPerPixel    = 4
        let bitsPerComponent = 8
        let bytesPerRow      = bytesPerPixel * width
        let bitmapInfo       = RGBA32.bitmapInfo

        guard let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo) else {
            print("unable to create context")
            return nil
        }

        guard let context2 = CGContext(data: nil, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo) else {
            print("unable to create context 2")
            return nil
        }

        context.draw(primary, in: CGRect(x: 0, y: 0, width: width, height: height))

        context2.draw(secondary, in: CGRect(x: 0, y: 0, width: width, height: height))

        guard let buffer = context.data else {
            print("Unable to get context data")
            return nil
        }

        guard let buffer2 = context2.data else {
            print("Unable to get context 2 data")
            return nil
        }

        let pixelBuffer = buffer.bindMemory(to: RGBA32.self, capacity: width * height)
        let pixelBuffer2 = buffer2.bindMemory(to: RGBA32.self, capacity: width * height)

        for row in 0 ..< Int(height) {
            if row % 10 == 0 {
                print("Row: \(row)")
            }

            for column in 0 ..< Int(width) {
                let offset = row * width + column

                let picture1 = pixelBuffer[offset]
                let picture2 = pixelBuffer2[offset]

                let minR = min(255,(UInt32(picture1.redComponent)+UInt32(picture2.redComponent))/2)
                let minG = min(255,(UInt32(picture1.greenComponent)+UInt32(picture2.greenComponent))/2)
                let minB = min(255,(UInt32(picture1.blueComponent)+UInt32(picture2.blueComponent))/2)
                let minA = min(255,(UInt32(picture1.alphaComponent)+UInt32(picture2.alphaComponent))/2)

                pixelBuffer[offset] = RGBA32(red: UInt8(minR), green: UInt8(minG), blue: UInt8(minB), alpha: UInt8(minA))
            }
        }

        let outputImage = context.makeImage()

        return outputImage
    }

    struct RGBA32: Equatable {
        //private var color: UInt32
        var color: UInt32

        var redComponent: UInt8 {
            return UInt8((color >> 24) & 255)
        }

        var greenComponent: UInt8 {
            return UInt8((color >> 16) & 255)
        }

        var blueComponent: UInt8 {
            return UInt8((color >> 8) & 255)
        }

        var alphaComponent: UInt8 {
            return UInt8((color >> 0) & 255)
        }

        init(red: UInt8, green: UInt8, blue: UInt8, alpha: UInt8) {
            let red   = UInt32(red)
            let green = UInt32(green)
            let blue  = UInt32(blue)
            let alpha = UInt32(alpha)
            color = (red << 24) | (green << 16) | (blue << 8) | (alpha << 0)
        }

        init(color: UInt32) {
            self.color = color
        }

        static let red     = RGBA32(red: 255, green: 0,   blue: 0,   alpha: 255)
        static let green   = RGBA32(red: 0,   green: 255, blue: 0,   alpha: 255)
        static let blue    = RGBA32(red: 0,   green: 0,   blue: 255, alpha: 255)
        static let white   = RGBA32(red: 255, green: 255, blue: 255, alpha: 255)
        static let black   = RGBA32(red: 0,   green: 0,   blue: 0,   alpha: 255)
        static let magenta = RGBA32(red: 255, green: 0,   blue: 255, alpha: 255)
        static let yellow  = RGBA32(red: 255, green: 255, blue: 0,   alpha: 255)
        static let cyan    = RGBA32(red: 0,   green: 255, blue: 255, alpha: 255)

        static let bitmapInfo = CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Little.rawValue

        static func ==(lhs: RGBA32, rhs: RGBA32) -> Bool {
            return lhs.color == rhs.color
        }
    }
</code>```

I'm not very experienced when it comes to working with RAW pixel values and there is probably room for much optimisation. The declaration of RGBA32 may not be required, but again I'm not sure how I'd go about simplifying the code. I've tried simply replacing that struct with a UInt32, however, as I divide by 2 the separation between the four channels gets messed up and I end up with the wrong result (on a positive note this brings the computing time down to about 6 seconds).

I've tried dropping the alpha channel (just hardcoding it to 255) and also dropping the safety checks that no values exceed 255. This has reduced the computing time to 19 seconds. However, it is far from the 6 seconds I was hoping to get close to and it would also be nice to average the alpha channel too.

Note: I am aware of CIFilters; however, darkening an image first, then using CIAdditionCompositing filter does not work as the API provided by Apple is actually using a more complex algorithm than straight forward addition. For more details on this, see here for my previous code on the subject and a similar question here with testing proving that Apple's API is not a straight forward addition of pixel values.

**Edit: ** Thanks to all the feedback I have now been able to make vast improvements. The by far biggest difference was to change from debug to release, that dropped the time by a lot. Then, I was able to write faster code for the modification of the RGBA values, eliminating the need for a separate struct for this. That changed the time from 23 seconds to about 10 (plus the debug to release improvements).  The code now looks like this, also being rewritten a bit to look more readable:

```<code>static func averageImages(primary: CGImage, secondary: CGImage) -> CGImage? {
    guard (primary.width == secondary.width && primary.height == secondary.height) else {
        return nil
    }

    let colorSpace       = CGColorSpaceCreateDeviceRGB()
    let width            = primary.width
    let height           = primary.height
    let bytesPerPixel    = 4
    let bitsPerComponent = 8
    let bytesPerRow      = bytesPerPixel * width
    let bitmapInfo       = CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Little.rawValue

    guard let primaryContext = CGContext(data: nil, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo),
        let secondaryContext = CGContext(data: nil, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo) else {
            print("unable to create context")
            return nil
    }

    primaryContext.draw(primary, in: CGRect(x: 0, y: 0, width: width, height: height))
    secondaryContext.draw(secondary, in: CGRect(x: 0, y: 0, width: width, height: height))

    guard let primaryBuffer = primaryContext.data, let secondaryBuffer = secondaryContext.data else {
        print("Unable to get context data")
        return nil
    }

    let primaryPixelBuffer = primaryBuffer.bindMemory(to: UInt32.self, capacity: width * height)
    let secondaryPixelBuffer = secondaryBuffer.bindMemory(to: UInt32.self, capacity: width * height)

    for row in 0 ..< Int(height) {
        if row % 10 == 0 {
            print("Row: \(row)")
        }

        for column in 0 ..< Int(width) {
            let offset = row * width + column

            let primaryPixel = primaryPixelBuffer[offset]
            let secondaryPixel = secondaryPixelBuffer[offset]

            let red = (((primaryPixel >> 24) & 255)/2 + ((secondaryPixel >> 24) & 255)/2) << 24
            let green = (((primaryPixel >> 16) & 255)/2 + ((secondaryPixel >> 16) & 255)/2) << 16
            let blue = (((primaryPixel >> 8) & 255)/2 + ((secondaryPixel >> 8) & 255)/2) << 8
            let alpha = ((primaryPixel & 255)/2 + (secondaryPixel & 255)/2)

            primaryPixelBuffer[offset] = red | green | blue | alpha
        }
    }

    print("Done looping")
    let outputImage = primaryContext.makeImage()

    return outputImage
}
</code>```

As for multithreading, I am going to run this function several times, and will therefore implement the multithreading over the iterations of the function rather than within the function itself. I do expect to get an even greater performance boost from this, but it also has to be balanced with the increased memory allocation of having more images in memory at the same time.

Thanks to everyone who contributed to this. Since all feedback has been through comments I can't mark any of them as the right answer. I also don't want to post my updated code as an answer as I wasn't the one who really made the answer. Any suggestions on how to proceed?

答:
This is a little bit hacky but will work and is the algorithm you are looking for.  Use vImageMatrixMultiply_Planar< channel fmt >() to scale each layer and add them together. The matrix coefficient for the layer is the weight for that layer, presumably 1/N for N layers, if you want them equally weighted.  </p>

<p>Since we are using a planar function on possibly interleaved data, you'll need to multiply the width of the src and dest buffers by the number of channels in the image. </p>

ContentLicense: CC BY-SA 4.0

Title: Slow performance of CGImage averaging

Body:
I am trying to create an image from an average of multiple images. The way I do this is to loop through the pixel value of 2 photos, add them together and divide by two. Simple math. However, while this is working, it is extremely slow (about 23 seconds to average 2x 10MP photos on a maximum specced MacBook Pro 15" 2016, compared to very much less time using Apples CIFilter API for similar algorithms). The code I'm currently using is this, based on another StackOverflow question here:

static func averageImages(primary: CGImage, secondary: CGImage) -> CGImage? {
        guard (primary.width == secondary.width && primary.height == secondary.height) else {
            return nil
        }

        let colorSpace       = CGColorSpaceCreateDeviceRGB()
        let width            = primary.width
        let height           = primary.height
        let bytesPerPixel    = 4
        let bitsPerComponent = 8
        let bytesPerRow      = bytesPerPixel * width
        let bitmapInfo       = RGBA32.bitmapInfo

        guard let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo) else {
            print("unable to create context")
            return nil
        }

        guard let context2 = CGContext(data: nil, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo) else {
            print("unable to create context 2")
            return nil
        }

        context.draw(primary, in: CGRect(x: 0, y: 0, width: width, height: height))

        context2.draw(secondary, in: CGRect(x: 0, y: 0, width: width, height: height))

        guard let buffer = context.data else {
            print("Unable to get context data")
            return nil
        }

        guard let buffer2 = context2.data else {
            print("Unable to get context 2 data")
            return nil
        }

        let pixelBuffer = buffer.bindMemory(to: RGBA32.self, capacity: width * height)
        let pixelBuffer2 = buffer2.bindMemory(to: RGBA32.self, capacity: width * height)

        for row in 0 ..< Int(height) {
            if row % 10 == 0 {
                print("Row: \(row)")
            }

            for column in 0 ..< Int(width) {
                let offset = row * width + column

                let picture1 = pixelBuffer[offset]
                let picture2 = pixelBuffer2[offset]

                let minR = min(255,(UInt32(picture1.redComponent)+UInt32(picture2.redComponent))/2)
                let minG = min(255,(UInt32(picture1.greenComponent)+UInt32(picture2.greenComponent))/2)
                let minB = min(255,(UInt32(picture1.blueComponent)+UInt32(picture2.blueComponent))/2)
                let minA = min(255,(UInt32(picture1.alphaComponent)+UInt32(picture2.alphaComponent))/2)

                pixelBuffer[offset] = RGBA32(red: UInt8(minR), green: UInt8(minG), blue: UInt8(minB), alpha: UInt8(minA))
            }
        }

        let outputImage = context.makeImage()

        return outputImage
    }

    struct RGBA32: Equatable {
        //private var color: UInt32
        var color: UInt32

        var redComponent: UInt8 {
            return UInt8((color >> 24) & 255)
        }

        var greenComponent: UInt8 {
            return UInt8((color >> 16) & 255)
        }

        var blueComponent: UInt8 {
            return UInt8((color >> 8) & 255)
        }

        var alphaComponent: UInt8 {
            return UInt8((color >> 0) & 255)
        }

        init(red: UInt8, green: UInt8, blue: UInt8, alpha: UInt8) {
            let red   = UInt32(red)
            let green = UInt32(green)
            let blue  = UInt32(blue)
            let alpha = UInt32(alpha)
            color = (red << 24) | (green << 16) | (blue << 8) | (alpha << 0)
        }

        init(color: UInt32) {
            self.color = color
        }

        static let red     = RGBA32(red: 255, green: 0,   blue: 0,   alpha: 255)
        static let green   = RGBA32(red: 0,   green: 255, blue: 0,   alpha: 255)
        static let blue    = RGBA32(red: 0,   green: 0,   blue: 255, alpha: 255)
        static let white   = RGBA32(red: 255, green: 255, blue: 255, alpha: 255)
        static let black   = RGBA32(red: 0,   green: 0,   blue: 0,   alpha: 255)
        static let magenta = RGBA32(red: 255, green: 0,   blue: 255, alpha: 255)
        static let yellow  = RGBA32(red: 255, green: 255, blue: 0,   alpha: 255)
        static let cyan    = RGBA32(red: 0,   green: 255, blue: 255, alpha: 255)

        static let bitmapInfo = CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Little.rawValue

        static func ==(lhs: RGBA32, rhs: RGBA32) -> Bool {
            return lhs.color == rhs.color
        }
    }

I'm not very experienced when it comes to working with RAW pixel values and there is probably room for much optimisation. The declaration of RGBA32 may not be required, but again I'm not sure how I'd go about simplifying the code. I've tried simply replacing that struct with a UInt32, however, as I divide by 2 the separation between the four channels gets messed up and I end up with the wrong result (on a positive note this brings the computing time down to about 6 seconds).

I've tried dropping the alpha channel (just hardcoding it to 255) and also dropping the safety checks that no values exceed 255. This has reduced the computing time to 19 seconds. However, it is far from the 6 seconds I was hoping to get close to and it would also be nice to average the alpha channel too.

Note: I am aware of CIFilters; however, darkening an image first, then using CIAdditionCompositing filter does not work as the API provided by Apple is actually using a more complex algorithm than straight forward addition. For more details on this, see here for my previous code on the subject and a similar question here with testing proving that Apple's API is not a straight forward addition of pixel values.

**Edit: ** Thanks to all the feedback I have now been able to make vast improvements. The by far biggest difference was to change from debug to release, that dropped the time by a lot. Then, I was able to write faster code for the modification of the RGBA values, eliminating the need for a separate struct for this. That changed the time from 23 seconds to about 10 (plus the debug to release improvements).  The code now looks like this, also being rewritten a bit to look more readable:

static func averageImages(primary: CGImage, secondary: CGImage) -> CGImage? {
    guard (primary.width == secondary.width && primary.height == secondary.height) else {
        return nil
    }

    let colorSpace       = CGColorSpaceCreateDeviceRGB()
    let width            = primary.width
    let height           = primary.height
    let bytesPerPixel    = 4
    let bitsPerComponent = 8
    let bytesPerRow      = bytesPerPixel * width
    let bitmapInfo       = CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Little.rawValue

    guard let primaryContext = CGContext(data: nil, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo),
        let secondaryContext = CGContext(data: nil, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo) else {
            print("unable to create context")
            return nil
    }

    primaryContext.draw(primary, in: CGRect(x: 0, y: 0, width: width, height: height))
    secondaryContext.draw(secondary, in: CGRect(x: 0, y: 0, width: width, height: height))

    guard let primaryBuffer = primaryContext.data, let secondaryBuffer = secondaryContext.data else {
        print("Unable to get context data")
        return nil
    }

    let primaryPixelBuffer = primaryBuffer.bindMemory(to: UInt32.self, capacity: width * height)
    let secondaryPixelBuffer = secondaryBuffer.bindMemory(to: UInt32.self, capacity: width * height)

    for row in 0 ..< Int(height) {
        if row % 10 == 0 {
            print("Row: \(row)")
        }

        for column in 0 ..< Int(width) {
            let offset = row * width + column

            let primaryPixel = primaryPixelBuffer[offset]
            let secondaryPixel = secondaryPixelBuffer[offset]

            let red = (((primaryPixel >> 24) & 255)/2 + ((secondaryPixel >> 24) & 255)/2) << 24
            let green = (((primaryPixel >> 16) & 255)/2 + ((secondaryPixel >> 16) & 255)/2) << 16
            let blue = (((primaryPixel >> 8) & 255)/2 + ((secondaryPixel >> 8) & 255)/2) << 8
            let alpha = ((primaryPixel & 255)/2 + (secondaryPixel & 255)/2)

            primaryPixelBuffer[offset] = red | green | blue | alpha
        }
    }

    print("Done looping")
    let outputImage = primaryContext.makeImage()

    return outputImage
}

As for multithreading, I am going to run this function several times, and will therefore implement the multithreading over the iterations of the function rather than within the function itself. I do expect to get an even greater performance boost from this, but it also has to be balanced with the increased memory allocation of having more images in memory at the same time.

Thanks to everyone who contributed to this. Since all feedback has been through comments I can't mark any of them as the right answer. I also don't want to post my updated code as an answer as I wasn't the one who really made the answer. Any suggestions on how to proceed?

Body:
This is a little bit hacky but will work and is the algorithm you are looking for.  Use vImageMatrixMultiply_Planar< channel fmt >() to scale each layer and add them together. The matrix coefficient for the layer is the weight for that layer, presumably 1/N for N layers, if you want them equally weighted.

Since we are using a planar function on possibly interleaved data, you'll need to multiply the width of the src and dest buffers by the number of channels in the image.


问:
Using the value in one column to specify from which row to retrieve a value for a new column
I'm looking for an automated way of converting this:

dat = tribble(
    ~a, ~b, ~c
    , 'x', 1, 'y'
    , 'y', 2, NA
    , 'q', 4, NA
    , 'z', 3, 'q'
)
```

<p>to:</p>

<pre class="lang-r prettyprint-override"><code>tribble(
    ~a, ~b, ~d
    , 'x', 1, 2
    , 'z', 3, 4
)
</code>```

So, the column c in dat encodes which row in dat to look at to grab a value for a new column d, and if c is NA, toss that row from the output. Any tips?

答:
We create the 'd' with lead of 'b' and filter out the NA rows of 'c' and remove the c column with select

```<code>library(dplyr)
dat %>%
    mutate(d = lead(b)) %>%
    filter(!is.na(c)) %>%
    select(-c)
# A tibble: 2 x 3
# a         b     d
#  <chr> <dbl> <dbl>
#1 x         1     2
#2 z         3     4
</code>```

Or more compactly

```<code>dat %>%
    mutate(d = replace(lead(b), is.na(c), NA), c = NULL) %>%
    na.omit
</code>```

Or with fill

```<code>library(tidyr)
dat %>%
   mutate(c1 = c) %>%
   fill(c1) %>%
   group_by(c1) %>%
   mutate(d = lead(b)) %>%
   ungroup %>%
   filter(!is.na(c)) %>%
   select(-c, -c1)
</code>```

Or in data.table

```<code>library(data.table)
setDT(dat)[, d := shift(b, type = 'lead')][!is.na(c)][, c := NULL][]
#   a b d
#1: x 1 2
#2: z 3 4
</code>```

NOTE: Both the solutions are simple and doesn't require any joins.  Besides, it gives the expected output in the OP's post

Or using match from base R

```<code>cbind(na.omit(dat), d = with(dat, b[match(c, a, nomatch = 0)]))[, -3]
#  a b d
#1 x 1 2
#2 z 3 4
</code>```

Body:
I'm looking for an automated way of converting this:

dat = tribble(
    ~a, ~b, ~c
    , 'x', 1, 'y'
    , 'y', 2, NA
    , 'q', 4, NA
    , 'z', 3, 'q'
)

to:

tribble(
    ~a, ~b, ~d
    , 'x', 1, 2
    , 'z', 3, 4
)

So, the column c in dat encodes which row in dat to look at to grab a value for a new column d, and if c is NA, toss that row from the output. Any tips?

Body:
We create the 'd' with lead of 'b' and filter out the NA rows of 'c' and remove the c column with select

library(dplyr)
dat %>%
    mutate(d = lead(b)) %>%
    filter(!is.na(c)) %>%
    select(-c)
# A tibble: 2 x 3
# a         b     d
#  <chr> <dbl> <dbl>
#1 x         1     2
#2 z         3     4

Or more compactly

dat %>%
    mutate(d = replace(lead(b), is.na(c), NA), c = NULL) %>%
    na.omit

Or with fill

library(tidyr)
dat %>%
   mutate(c1 = c) %>%
   fill(c1) %>%
   group_by(c1) %>%
   mutate(d = lead(b)) %>%
   ungroup %>%
   filter(!is.na(c)) %>%
   select(-c, -c1)

Or in data.table

library(data.table)
setDT(dat)[, d := shift(b, type = 'lead')][!is.na(c)][, c := NULL][]
#   a b d
#1: x 1 2
#2: z 3 4

NOTE: Both the solutions are simple and doesn't require any joins.  Besides, it gives the expected output in the OP's post

Or using match from base R

cbind(na.omit(dat), d = with(dat, b[match(c, a, nomatch = 0)]))[, -3]
#  a b d
#1 x 1 2
#2 z 3 4


问:
Angular routing adding random scrollbars
I'm currently having this issue with angular after I hooked up my components to routing where scroll bars would appear all over my page and scrolling would be really buggy. My components worked fine until I added routing. In one of my pages, the page scrolls but the content would not display. It's sort of hard to explain but I've included a screenshot. In another component that has a max-height of 100vh, it added a scroll bar and if I scroll down I would see parts of another component.

答: I solved my problem, it was a rather simple fix. My editor for some reason had a component hidden so on my app.component I had a component for one of my pages with router-outlet. I just had to remove the page component to fix the issue.</p>


问:
RecursionError in Python Using Hylang
First off let me just say I know what I'm doing is not ideal, but I'm trying to write the member? function from The Little Schemer using Hy.

```<code>(setv else True)

(defn null? [lst]
  " If list is empty return True else False "
  (if lst
      False
      True))

(defn member? [a lat]
  " Checks if value is a member of a list "
  (cond
    [(null? lat) False]
    [else (or (= (first lat) a)
              (member? a (rest lat)))]))

(print (member? 1 '(2 3 4 1)))
</code>```

This works exactly how I expect. The problem is, if the list is greater than 4 elements long I get the error

```<code>RecursionError: maximum recursion depth exceeded while calling a Python object
</code>```

I know Python isn't meant to do recursion and in the Python docs it even says that there is a default recursion limit to keep the C stack from overflowing. On my machine getrecursionlimit() yields the value of 1000, and I was able to successfully set it to over 20,000 before getting a segfault. Even with it set to 20,000 I am still getting the error on a list of 5 elements. What I don't understand is... How am I hitting over 20,000 levels of recursion on a 5 element list?

And for those curious I'm using Python 3.6.5, MacOS Mojave version 10.14.6 on a 15" Macbook pro, Hylang version 0.18.0, and the output of my program using hy2py is

```<code>from hy.core.language import first, rest
from hy import HyExpression, HyInteger
hyx_else = True

def is_null(lst):
    """ If list is empty return True else False """
    return False if lst else True

def is_member(a, lat):
    """ Checks if value is a member of a list """
    return False if is_null(lat) else first(lat) == a or is_member(a, rest(lat)
        ) if hyx_else else None

print(is_member(1, HyExpression([] + [HyInteger(2)] + [HyInteger(3)] + [
    HyInteger(4)] + [HyInteger(5)] + [HyInteger(1)])))
</code>```

答: I can't reproduce this on Hy master. It's probably a bug that was fixed since 0.18.0.</p>

Title: RecursionError in Python Using Hylang

Body:
First off let me just say I know what I'm doing is not ideal, but I'm trying to write the member? function from The Little Schemer using Hy.

(setv else True)

(defn null? [lst]
  " If list is empty return True else False "
  (if lst
      False
      True))

(defn member? [a lat]
  " Checks if value is a member of a list "
  (cond
    [(null? lat) False]
    [else (or (= (first lat) a)
              (member? a (rest lat)))]))

(print (member? 1 '(2 3 4 1)))

This works exactly how I expect. The problem is, if the list is greater than 4 elements long I get the error

RecursionError: maximum recursion depth exceeded while calling a Python object

I know Python isn't meant to do recursion and in the Python docs it even says that there is a default recursion limit to keep the C stack from overflowing. On my machine getrecursionlimit() yields the value of 1000, and I was able to successfully set it to over 20,000 before getting a segfault. Even with it set to 20,000 I am still getting the error on a list of 5 elements. What I don't understand is... How am I hitting over 20,000 levels of recursion on a 5 element list?

And for those curious I'm using Python 3.6.5, MacOS Mojave version 10.14.6 on a 15" Macbook pro, Hylang version 0.18.0, and the output of my program using hy2py is

from hy.core.language import first, rest
from hy import HyExpression, HyInteger
hyx_else = True

def is_null(lst):
    """ If list is empty return True else False """
    return False if lst else True

def is_member(a, lat):
    """ Checks if value is a member of a list """
    return False if is_null(lat) else first(lat) == a or is_member(a, rest(lat)
        ) if hyx_else else None

print(is_member(1, HyExpression([] + [HyInteger(2)] + [HyInteger(3)] + [
    HyInteger(4)] + [HyInteger(5)] + [HyInteger(1)])))


问:
Can we extract image from LPLinkView in LinkPresentation framework?
I want to present a rich link in my app and also send those data to my server.
I need to access the image inside the view of LPLinkView.

how can I access the parameters inside it? (like: image, description, title, icon, and ext...)

答:
Unfortunately, you can't access any internal properties of an LPLinkView, but you can easily create your own view. The LPLinkMetadata object has everything you need, you just need to know how to extract the images from its iconProvider and imageProvider, which are subclasses of NSItemProvider.

UIKit (iOS)

You can use NSItemProvdier's loadObject(ofClass:) method to easily get a UIImage. This works because UIImage conforms to the NSItemProviderReading protocol.

import LinkPresentation
import UIKit

let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))

let url = URL(string: "https://stackoverflow.com/q/61286308/2101447")!

LPMetadataProvider().startFetchingMetadata(for: url) { (linkMetadata, error) in
    guard let linkMetadata = linkMetadata, let imageProvider = linkMetadata.iconProvider else { return }

    print(linkMetadata.title ?? "Untitled")

    imageProvider.loadObject(ofClass: UIImage.self) { (image, error) in
        guard error == nil else {
            // handle error
            return
        }

        if let image = image as? UIImage {
            // do something with image
            DispatchQueue.main.async {
                imageView.image = image
            }
        } else {
            print("no image available")
        }
    }
}
```

<h2>SwiftUI</h2>

<p>SwiftUI's <code>Image</code> is a <code>struct</code>, so it cannot conform to <code>NSItemProviderReading</code>. It's easiest to use the UIKit code above to obtain a <code>UIImage</code> and instantiate a SwiftUI <code>Image</code> from that.</p>

<pre class="lang-swift prettyprint-override"><code>...

if let uiImage = loadedImage as? UIImage {
    let image = Image(uiImage: uiImage)
}
</code>```

AppKit (macOS)

Unlike its UIImage sister, NSImage does not conform to NSItemProviderReading, which means you'll have to use NSItemProvdier's older loadItem(forTypeIdentifier:options:) method.

You'll need to specify the typeIdentifier and initialize the NSImage from Data yourself, but otherwise it's pretty much the same.

import CoreServices // may be necessary for kUTTypeImage
import LinkPresentation
import AppKit

let imageView = NSImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))

let url = URL(string: "https://stackoverflow.com/q/61286308/2101447")!

LPMetadataProvider().startFetchingMetadata(for: url) { (linkMetadata, error) in
    guard let linkMetadata = linkMetadata, let imageProvider = linkMetadata.iconProvider else { return }

    print(linkMetadata.title ?? "Untitled")

    imageProvider.loadItem(forTypeIdentifier: kUTTypeImage as String, options: nil) { (data, error) in
        guard error == nil else {
            // handle error
            return
        }
        guard let data = data as? Data else {
            print("no image available")
            return
        }
        if let image = NSImage(data: data) {
            // do something with image
            DispatchQueue.main.async {
                self.imageView.image = image
            }
        } else {
            print("no image available")
        }
    }
}
```

Body:
Unfortunately, you can't access any internal properties of an LPLinkView, but you can easily create your own view. The LPLinkMetadata object has everything you need, you just need to know how to extract the images from its iconProvider and imageProvider, which are subclasses of NSItemProvider.

UIKit (iOS)

You can use NSItemProvdier's loadObject(ofClass:) method to easily get a UIImage. This works because UIImage conforms to the NSItemProviderReading protocol.

import LinkPresentation
import UIKit

let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))

let url = URL(string: "https://stackoverflow.com/q/61286308/2101447")!

LPMetadataProvider().startFetchingMetadata(for: url) { (linkMetadata, error) in
    guard let linkMetadata = linkMetadata, let imageProvider = linkMetadata.iconProvider else { return }

    print(linkMetadata.title ?? "Untitled")

    imageProvider.loadObject(ofClass: UIImage.self) { (image, error) in
        guard error == nil else {
            // handle error
            return
        }

        if let image = image as? UIImage {
            // do something with image
            DispatchQueue.main.async {
                imageView.image = image
            }
        } else {
            print("no image available")
        }
    }
}

SwiftUI

SwiftUI's Image is a struct, so it cannot conform to NSItemProviderReading. It's easiest to use the UIKit code above to obtain a UIImage and instantiate a SwiftUI Image from that.

...

if let uiImage = loadedImage as? UIImage {
    let image = Image(uiImage: uiImage)
}

AppKit (macOS)

Unlike its UIImage sister, NSImage does not conform to NSItemProviderReading, which means you'll have to use NSItemProvdier's older loadItem(forTypeIdentifier:options:) method.

You'll need to specify the typeIdentifier and initialize the NSImage from Data yourself, but otherwise it's pretty much the same.

import CoreServices // may be necessary for kUTTypeImage
import LinkPresentation
import AppKit

let imageView = NSImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))

let url = URL(string: "https://stackoverflow.com/q/61286308/2101447")!

LPMetadataProvider().startFetchingMetadata(for: url) { (linkMetadata, error) in
    guard let linkMetadata = linkMetadata, let imageProvider = linkMetadata.iconProvider else { return }

    print(linkMetadata.title ?? "Untitled")

    imageProvider.loadItem(forTypeIdentifier: kUTTypeImage as String, options: nil) { (data, error) in
        guard error == nil else {
            // handle error
            return
        }
        guard let data = data as? Data else {
            print("no image available")
            return
        }
        if let image = NSImage(data: data) {
            // do something with image
            DispatchQueue.main.async {
                self.imageView.image = image
            }
        } else {
            print("no image available")
        }
    }
}


问:
nginx always adding trailing slash after domain
I've spent forever searching and I can't see that I'm doing anything wrong.

Basically I have two domains and want to route to a backend service depending on which one is visited.

clientkey.local

clientkey.strapi.local

When I visit each of these domains, it's rewriting the urls as:

clientkey.local/

clientkey.strapi.local/

There is no point to adding the extra slashes if I'm just visiting the base domain. I can add the trailing slash if I want and still end up on the home page, but it shouldn't redirect me there automatically. Below is my nginx config.

Any ideas? I'm using docker-compose if that matters. I feel like I'm missing something obvious.

```<code>worker_processes 4;

events { worker_connections 1024; }

http {
    upstream strapi_servers {
        server strapi:1337;
    }

    upstream gallery_servers {
        server gallery;
    }

    server {
        listen 80;
        server_name clientkey.strapi.local;
        location / {
            proxy_pass http://strapi_servers;
            proxy_http_version 1.1;
            proxy_set_header X-Forwarded-Host $host;
            proxy_set_header X-Forwarded-Server $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_set_header Host $http_host;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "Upgrade";
            proxy_pass_request_headers on;
        }
    }

    server {
        listen 80;
        server_name clientkey.local;
        location / {
            proxy_pass http://gallery_servers;
            proxy_redirect     off;
            proxy_set_header   Host $host;
            proxy_set_header   X-Real-IP $remote_addr;
            proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header   X-Forwarded-Host $server_name;
        }
    }
}
</code>```

答:
Quick testing reveals that slash is not hidden for non-public TLD websites (Chromium/Chrome).

In other words, if the TLD isn't real, then slash is not being ommited.

example.local - slash shown

example.anyting-non-real - slash shown

example.com - slash hidden

Body:
I've spent forever searching and I can't see that I'm doing anything wrong.

Basically I have two domains and want to route to a backend service depending on which one is visited.

clientkey.local

clientkey.strapi.local

When I visit each of these domains, it's rewriting the urls as:

clientkey.local/

clientkey.strapi.local/

There is no point to adding the extra slashes if I'm just visiting the base domain. I can add the trailing slash if I want and still end up on the home page, but it shouldn't redirect me there automatically. Below is my nginx config.

Any ideas? I'm using docker-compose if that matters. I feel like I'm missing something obvious.

worker_processes 4;

events { worker_connections 1024; }

http {
    upstream strapi_servers {
        server strapi:1337;
    }

    upstream gallery_servers {
        server gallery;
    }

    server {
        listen 80;
        server_name clientkey.strapi.local;
        location / {
            proxy_pass http://strapi_servers;
            proxy_http_version 1.1;
            proxy_set_header X-Forwarded-Host $host;
            proxy_set_header X-Forwarded-Server $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_set_header Host $http_host;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "Upgrade";
            proxy_pass_request_headers on;
        }
    }

    server {
        listen 80;
        server_name clientkey.local;
        location / {
            proxy_pass http://gallery_servers;
            proxy_redirect     off;
            proxy_set_header   Host $host;
            proxy_set_header   X-Real-IP $remote_addr;
            proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header   X-Forwarded-Host $server_name;
        }
    }
}