问:
possible to merge the same video to one single video
I want to merge a same video to one single video together. I searched already in the internet for a possible solution. I implemented some code, but the problem is that it won't merge all the videos. The end result is only the first video with a few seconds. I don't know what Im doing wrong.

This is my code:

```<code>var atTimeM: CMTime = CMTimeMake(value: 0, timescale: 0)
var layerInstructionsArray = [AVVideoCompositionLayerInstruction]()
var completeTrackDuration: CMTime = CMTimeMake(value: 0, timescale: 1)
var videoSize: CGSize = CGSize(width: 0.0, height: 0.0)
var totalTime : CMTime = CMTimeMake(value: 0, timescale: 0)
var videoArrayOfAssets = [AVAsset]()

func mergeVideoArray(){

    print(videoArrayOfAssets)

   let mixComposition = AVMutableComposition()
    for videoAsset in videoArrayOfAssets {
        let videoTrack =
            mixComposition.addMutableTrack(withMediaType: AVMediaType.video,
                                           preferredTrackID: Int32(kCMPersistentTrackID_Invalid))
        do {
            if videoAsset == videoArrayOfAssets.first {
                atTimeM = CMTime.zero
            } else {
                atTimeM = totalTime // <-- Use the total time for all the videos seen so far.
            }
            try videoTrack!.insertTimeRange(CMTimeRangeMake(start: CMTime.zero, duration: videoAsset.duration),
                                            of: videoAsset.tracks(withMediaType: AVMediaType.video)[0],
                                           at: atTimeM)
            videoSize = videoTrack!.naturalSize
        } catch let error as NSError {
            print("error: \(error)")
        }
        completeTrackDuration = CMTimeAdd(completeTrackDuration, videoAsset.duration)
        let videoInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: videoTrack!)
        if (videoAsset != videoArrayOfAssets.last) {
            videoInstruction.setOpacity(0.0, at: completeTrackDuration)

        }
        layerInstructionsArray.append(videoInstruction)
    }

    let mainInstruction = AVMutableVideoCompositionInstruction()
    mainInstruction.timeRange = CMTimeRangeMake(start: CMTime.zero, duration: completeTrackDuration)
    mainInstruction.layerInstructions = layerInstructionsArray

    let mainComposition = AVMutableVideoComposition()
    mainComposition.instructions = [mainInstruction]
    mainComposition.frameDuration = CMTimeMake(value: 1, timescale: 30)
    mainComposition.renderSize = CGSize(width: videoSize.width, height: videoSize.height)

    let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
    let dateFormatter = DateFormatter()
    dateFormatter.dateStyle = .long
    dateFormatter.timeStyle = .short
    let date = dateFormatter.string(from: NSDate() as Date)
    let savePath = (documentDirectory as NSString).appendingPathComponent("mergeVideo-\(date).mov")
    let url = NSURL(fileURLWithPath: savePath)

    let exporter = AVAssetExportSession(asset: mixComposition, presetName: AVAssetExportPresetHighestQuality)
    exporter!.outputURL = url as URL
    exporter!.outputFileType = AVFileType.mov
    exporter!.shouldOptimizeForNetworkUse = true
    exporter!.videoComposition = mainComposition
    exporter!.exportAsynchronously {

        PHPhotoLibrary.shared().performChanges({
            PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: exporter!.outputURL!)
        }) { saved, error in
            if saved {
                print("video saved to camera roll")
        }
    }
}
}
</code>```

How I can manage this to work?

答:
You can use the class created by me for similar purpose:</p>

```<code>import Foundation
import CoreMedia
import AVFoundation

public protocol MediaItemProtocol {
    var duration: CMTime {get}
    var asset: AVAsset {get}
    func createFileOnDisk(completionHandler: @escaping (_ fileURL: URL?, _ error: Error?) -> Void)
}

final public class VideoMediaItem: MediaItemProtocol {
    public private (set) var duration: CMTime
    public private (set) var asset: AVAsset
    private var videoUrl: URL
    public init(url: URL) {
        videoUrl = url
        let options = [AVURLAssetPreferPreciseDurationAndTimingKey: true]
        let asset = AVURLAsset(url: url, options: options)
        self.asset = asset
        duration = asset.duration
    }
    public func createFileOnDisk(completionHandler: @escaping (_ fileURL: URL?, _ error: Error?) -> Void) {
        completionHandler(videoUrl, nil)
    }
}

final class VideoCompositionMediaItem: MediaItemProtocol {
    private (set) var duration: CMTime = kCMTimeZero
    private (set) var asset: AVAsset
    private var itemList: [MediaItemProtocol]
    private var exporter: AVAssetExportSession?
    init(item: [MediaItemProtocol]) {
        self.itemList = item
        let composition = AVMutableComposition()
        for mediaItem in item {
            if CMTIME_IS_VALID(mediaItem.duration) {
                let itemDuration = mediaItem.duration
                let range = CMTimeRangeMake(kCMTimeZero, itemDuration)
                try? composition.insertTimeRange(range, of: mediaItem.asset, at: duration)
                duration = CMTimeAdd(duration, itemDuration)
            }
        }

        if let track = item.first?.asset.tracks(withMediaType: .video).first {
            if let compositionTrack = composition.tracks(withMediaType: .video).first {
                compositionTrack.preferredTransform = track.preferredTransform
            }
        }

        asset = composition
    }

    func createFileOnDisk(completionHandler: @escaping (_ fileURL: URL?, _ error: Error?) -> Void) {
        if self.exporter != nil {
            completionHandler(nil, MediaItemError.AlreadyExporting)
            return
        }
        exporter = AVAssetExportSession(asset: asset, presetName: AVAssetExportPreset1280x720)
        guard let exporter = exporter else {
            completionHandler(nil, MediaItemError.UnknownError)
            return
        }
        let fileURL = URL(fileURLWithPath: NSTemporaryDirectory())
            .appendingPathComponent("Composition" + NSUUID().uuidString)
            .appendingPathExtension("mov")

        exporter.outputURL = fileURL
        exporter.outputFileType = AVFileType.mov
        exporter.shouldOptimizeForNetworkUse = true
        exporter.timeRange = CMTimeRangeMake(kCMTimeZero, duration)
        exporter.exportAsynchronously {
            if self.exporter?.status == .completed {
                self.exporter = nil
                completionHandler(fileURL, nil)
            } else {
                self.exporter = nil
                completionHandler(nil, MediaItemError.ErrorExporting)
            }
        }
    }

}
</code>```

Body:
I want to merge a same video to one single video together. I searched already in the internet for a possible solution. I implemented some code, but the problem is that it won't merge all the videos. The end result is only the first video with a few seconds. I don't know what Im doing wrong.

This is my code:

var atTimeM: CMTime = CMTimeMake(value: 0, timescale: 0)
var layerInstructionsArray = [AVVideoCompositionLayerInstruction]()
var completeTrackDuration: CMTime = CMTimeMake(value: 0, timescale: 1)
var videoSize: CGSize = CGSize(width: 0.0, height: 0.0)
var totalTime : CMTime = CMTimeMake(value: 0, timescale: 0)
var videoArrayOfAssets = [AVAsset]()

func mergeVideoArray(){

    print(videoArrayOfAssets)

   let mixComposition = AVMutableComposition()
    for videoAsset in videoArrayOfAssets {
        let videoTrack =
            mixComposition.addMutableTrack(withMediaType: AVMediaType.video,
                                           preferredTrackID: Int32(kCMPersistentTrackID_Invalid))
        do {
            if videoAsset == videoArrayOfAssets.first {
                atTimeM = CMTime.zero
            } else {
                atTimeM = totalTime // <-- Use the total time for all the videos seen so far.
            }
            try videoTrack!.insertTimeRange(CMTimeRangeMake(start: CMTime.zero, duration: videoAsset.duration),
                                            of: videoAsset.tracks(withMediaType: AVMediaType.video)[0],
                                           at: atTimeM)
            videoSize = videoTrack!.naturalSize
        } catch let error as NSError {
            print("error: \(error)")
        }
        completeTrackDuration = CMTimeAdd(completeTrackDuration, videoAsset.duration)
        let videoInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: videoTrack!)
        if (videoAsset != videoArrayOfAssets.last) {
            videoInstruction.setOpacity(0.0, at: completeTrackDuration)

        }
        layerInstructionsArray.append(videoInstruction)
    }

    let mainInstruction = AVMutableVideoCompositionInstruction()
    mainInstruction.timeRange = CMTimeRangeMake(start: CMTime.zero, duration: completeTrackDuration)
    mainInstruction.layerInstructions = layerInstructionsArray

    let mainComposition = AVMutableVideoComposition()
    mainComposition.instructions = [mainInstruction]
    mainComposition.frameDuration = CMTimeMake(value: 1, timescale: 30)
    mainComposition.renderSize = CGSize(width: videoSize.width, height: videoSize.height)

    let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
    let dateFormatter = DateFormatter()
    dateFormatter.dateStyle = .long
    dateFormatter.timeStyle = .short
    let date = dateFormatter.string(from: NSDate() as Date)
    let savePath = (documentDirectory as NSString).appendingPathComponent("mergeVideo-\(date).mov")
    let url = NSURL(fileURLWithPath: savePath)

    let exporter = AVAssetExportSession(asset: mixComposition, presetName: AVAssetExportPresetHighestQuality)
    exporter!.outputURL = url as URL
    exporter!.outputFileType = AVFileType.mov
    exporter!.shouldOptimizeForNetworkUse = true
    exporter!.videoComposition = mainComposition
    exporter!.exportAsynchronously {

        PHPhotoLibrary.shared().performChanges({
            PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: exporter!.outputURL!)
        }) { saved, error in
            if saved {
                print("video saved to camera roll")
        }
    }
}
}

How I can manage this to work?

Body:
You can use the class created by me for similar purpose:

import Foundation
import CoreMedia
import AVFoundation

public protocol MediaItemProtocol {
    var duration: CMTime {get}
    var asset: AVAsset {get}
    func createFileOnDisk(completionHandler: @escaping (_ fileURL: URL?, _ error: Error?) -> Void)
}

final public class VideoMediaItem: MediaItemProtocol {
    public private (set) var duration: CMTime
    public private (set) var asset: AVAsset
    private var videoUrl: URL
    public init(url: URL) {
        videoUrl = url
        let options = [AVURLAssetPreferPreciseDurationAndTimingKey: true]
        let asset = AVURLAsset(url: url, options: options)
        self.asset = asset
        duration = asset.duration
    }
    public func createFileOnDisk(completionHandler: @escaping (_ fileURL: URL?, _ error: Error?) -> Void) {
        completionHandler(videoUrl, nil)
    }
}

final class VideoCompositionMediaItem: MediaItemProtocol {
    private (set) var duration: CMTime = kCMTimeZero
    private (set) var asset: AVAsset
    private var itemList: [MediaItemProtocol]
    private var exporter: AVAssetExportSession?
    init(item: [MediaItemProtocol]) {
        self.itemList = item
        let composition = AVMutableComposition()
        for mediaItem in item {
            if CMTIME_IS_VALID(mediaItem.duration) {
                let itemDuration = mediaItem.duration
                let range = CMTimeRangeMake(kCMTimeZero, itemDuration)
                try? composition.insertTimeRange(range, of: mediaItem.asset, at: duration)
                duration = CMTimeAdd(duration, itemDuration)
            }
        }

        if let track = item.first?.asset.tracks(withMediaType: .video).first {
            if let compositionTrack = composition.tracks(withMediaType: .video).first {
                compositionTrack.preferredTransform = track.preferredTransform
            }
        }

        asset = composition
    }

    func createFileOnDisk(completionHandler: @escaping (_ fileURL: URL?, _ error: Error?) -> Void) {
        if self.exporter != nil {
            completionHandler(nil, MediaItemError.AlreadyExporting)
            return
        }
        exporter = AVAssetExportSession(asset: asset, presetName: AVAssetExportPreset1280x720)
        guard let exporter = exporter else {
            completionHandler(nil, MediaItemError.UnknownError)
            return
        }
        let fileURL = URL(fileURLWithPath: NSTemporaryDirectory())
            .appendingPathComponent("Composition" + NSUUID().uuidString)
            .appendingPathExtension("mov")

        exporter.outputURL = fileURL
        exporter.outputFileType = AVFileType.mov
        exporter.shouldOptimizeForNetworkUse = true
        exporter.timeRange = CMTimeRangeMake(kCMTimeZero, duration)
        exporter.exportAsynchronously {
            if self.exporter?.status == .completed {
                self.exporter = nil
                completionHandler(fileURL, nil)
            } else {
                self.exporter = nil
                completionHandler(nil, MediaItemError.ErrorExporting)
            }
        }
    }

}


来源: stackexchange

问:
write vba to auto filter between two values giving error
I have written code as below to filter a percentage field between two different values coming from two different fields:

Please find below:

These two values are numbers and the filter column is percentage.
I get the following error: AutoFilter method of Range class failed

With ActiveSheet.Range("A5:G" & LastRow)
    .AutoFilter Field:=6, Criteria1:=">=" & Worksheets("Project % Spent").Range("K5").Value, Operator:=xlAnd, Criteria2:="<=" & Worksheets("Project % Spent").Range("K6").Value
End With
```

Can anyone please help me out with what I should mention exactly?

答: Using .Value on 10% will return 0.1, not 10. Also, you can't have a number greater than 10.19, but less than -9.81. Try switching < and > and the code will work.</p>

ContentLicense: CC BY-SA 4.0

Body:
I have written code as below to filter a percentage field between two different values coming from two different fields:

Please find below:

These two values are numbers and the filter column is percentage.
I get the following error: AutoFilter method of Range class failed

With ActiveSheet.Range("A5:G" & LastRow)
    .AutoFilter Field:=6, Criteria1:=">=" & Worksheets("Project % Spent").Range("K5").Value, Operator:=xlAnd, Criteria2:="<=" & Worksheets("Project % Spent").Range("K6").Value
End With

Can anyone please help me out with what I should mention exactly?


问:
Custom checkbox without label's "for" attribute (Bootstrap 4)
Is there a way to still have the Bootstrap 4 custom checkbox styling without using the id on the input and the attribute for on the label? The styling for checked is not there when you remove it.

Example:

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

  <input type="checkbox" class="custom-control-input" id="customControlValidation1" required>
  Check this custom checkbox

```

I've tried wrapping the input with label, but that doesn't seem to do anything either. Is there a way I could avoid giving the input a static id and still get the Boostrap styled checkbox? Thanks!

答:
Here is simplest solution.
Label should be used as wrapper for checkbox being clickable.

  <input type="checkbox" name="checkbox-name" class="custom-control-input">

```

Body:
Is there a way to still have the Bootstrap 4 custom checkbox styling without using the id on the input and the attribute for on the label? The styling for checked is not there when you remove it.

Example:

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

  <input type="checkbox" class="custom-control-input" id="customControlValidation1" required>
  Check this custom checkbox

I've tried wrapping the input with label, but that doesn't seem to do anything either. Is there a way I could avoid giving the input a static id and still get the Boostrap styled checkbox? Thanks!

Body:
Here is simplest solution.
Label should be used as wrapper for checkbox being clickable.

<div class="custom-control custom-checkbox">
  <label><input type="checkbox" name="checkbox-name" class="custom-control-input">
    <div class="custom-control-label"></div>
    </label>
</div>


问:
How to get doctrine to generate sql with BIGINT type?
In my schema I have a number of field that need to be BIGINT. I use the following command from Symfony

symfony doctrine:build-sql
```

to generate my database. The fields always come out as type int. I have tried the following types in the schema:

int

{type: integer, notnull: true}

{type: integer(5), notnull: true}

{type: bigint, notnull: true}

None of them seem to work (I always rebuild the model before building the SQL).

What type should i put in the schema.yml?

答:
yes, integer(5) should do the work.

You can check other schema data types in The symfony and Doctrine book, but have in mind that it's version 1.2 and it's not maintained anymore.

Best regards.

Body:
In my schema I have a number of field that need to be BIGINT. I use the following command from Symfony

symfony doctrine:build-sql

to generate my database. The fields always come out as type int. I have tried the following types in the schema:

int

{type: integer, notnull: true}

{type: integer(5), notnull: true}

{type: bigint, notnull: true}

None of them seem to work (I always rebuild the model before building the SQL).

What type should i put in the schema.yml?

ContentLicense: CC BY-SA 3.0


问:
How to use multiple columns in Bootsrap not starting From column 1?
I have two buttons in page. According to W3Schools, the page is divided into 12 columns. I want the two buttons to be 4 columns wide but from column 2 to 5 and the second from column 8 to 11. How can I do this? I am using using bootstrap to do this.

Using empty 'p' elements doesn't seem to work as seen below.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

  <input type="button" id="cancel" name="cancel" value="Cancel" onclick="cancel();" class="col-sm-3">

  <input type="button" id="registerX" class="col-sm-3" name="registerX" value="Register" onclick="submitCheck();">

```

I can notice a bigger gap after the second button that the first gap. What can I do?

Edit: To see it open the code in a full page.

答:
In bootstrap you normally create a container, that you fill with rows, which are filled with columns. You applied the column classes directly to the buttons. While this may work, it's not how it was meant to work.

There are some nice examples in the bootstrap docs:
https://getbootstrap.com/docs/4.0/layout/grid/#offsetting-columns

Try this:

```<code><div class="container fluid">
  <div class="row">
    <div class="col-sm-4 offset-sm-1">
      <input class="btn btn-primary btn-block" type="button" name="cancel" value="Cancel">
    </div>
    <div class="col-sm-4 offset-sm-2">
      <input class="btn btn-primary btn-block" type="button" name="registerX" value="Register" >
    </div>
  </div>
</div>
</code>```

You can set your columns to 4 wide using the col-sm-4 class. You can shift them by using offset-sm-X where the X is the number of places you want to shift.

If you want your buttons to take up the full width of the columns you just created, you pass a class btn-block to them.

Example: https://jsfiddle.net/jkrielaars/cno6qhbx/7/

Body:
I have two buttons in page. According to W3Schools, the page is divided into 12 columns. I want the two buttons to be 4 columns wide but from column 2 to 5 and the second from column 8 to 11. How can I do this? I am using using bootstrap to do this.

Using empty 'p' elements doesn't seem to work as seen below.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

  <input type="button" id="cancel" name="cancel" value="Cancel" onclick="cancel();" class="col-sm-3">

  <input type="button" id="registerX" class="col-sm-3" name="registerX" value="Register" onclick="submitCheck();">

I can notice a bigger gap after the second button that the first gap. What can I do?

Edit: To see it open the code in a full page.

Body:
In bootstrap you normally create a container, that you fill with rows, which are filled with columns. You applied the column classes directly to the buttons. While this may work, it's not how it was meant to work.

There are some nice examples in the bootstrap docs:
https://getbootstrap.com/docs/4.0/layout/grid/#offsetting-columns

Try this:

<div class="container fluid">
  <div class="row">
    <div class="col-sm-4 offset-sm-1">
      <input class="btn btn-primary btn-block" type="button" name="cancel" value="Cancel">
    </div>
    <div class="col-sm-4 offset-sm-2">
      <input class="btn btn-primary btn-block" type="button" name="registerX" value="Register" >
    </div>
  </div>
</div>

You can set your columns to 4 wide using the col-sm-4 class. You can shift them by using offset-sm-X where the X is the number of places you want to shift.

If you want your buttons to take up the full width of the columns you just created, you pass a class btn-block to them.

Example: https://jsfiddle.net/jkrielaars/cno6qhbx/7/


问:
Making HTML5 datalist visible when focus event fires on input
As some might know already styling select element is a nightmare, literally impossible without some javascript trickery. The new datalist in HTML5 could serve the same purpose since the user is presented with a list of options and the value is recorded in an input text field.

The limitation here is the list does not appear until the user start typing something in the text field and even then is only shown possible matches based on their input. The behavior I want is that as soon as there is focus on the field the entire list of options become visible.

So I have this code - view on jsbin

```<code><!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Input - Datalist</title>
</head>
<body>
  <input list="categories">
  <datalist id="categories">
    <option value="Breakfast">Breakfast</option>
    <option value="Brunch">Brunch</option>
    <option value="Lunch">Lunch</option>
    <option value="Dinner">Dinner</option>
    <option value="Desserts">Desserts</option>
  </datalist>
</body>
</html>
</code>```

and I'm trying to get that to show with this Javascript:

```<code>    var catVal = document.getElementsByTagName("input")[0],
    cat = document.getElementById("categories");

    catVal.style.fontSize = "1.3em";

    catVal.addEventListener("focus", function(event){
     cat.style.display = "block";
    }, false);
</code>```

Any help would be appreciated,

Cheers

答:
Question is pretty old, but it's top search on google and there are no answers to be found so I'll add it here.

To expand datalist on first click you need to set

```<code>dataListElement.style.display = "block";
</code>```

and immediately hide it in next line, so it does not appear as element in your DOM, but it will only expand it under input element.

```<code>dataListElement.style.display = "none";
</code>```

As of today it's not expanded on first click only in Firefox.

Body:
As some might know already styling select element is a nightmare, literally impossible without some javascript trickery. The new datalist in HTML5 could serve the same purpose since the user is presented with a list of options and the value is recorded in an input text field.

The limitation here is the list does not appear until the user start typing something in the text field and even then is only shown possible matches based on their input. The behavior I want is that as soon as there is focus on the field the entire list of options become visible.

So I have this code - view on jsbin

<!DOCTYPE html>

<meta charset=utf-8 />
<title>Input - Datalist</title>

  <input list="categories">
  <datalist id="categories">
    <option value="Breakfast">Breakfast</option>
    <option value="Brunch">Brunch</option>
    <option value="Lunch">Lunch</option>
    <option value="Dinner">Dinner</option>
    <option value="Desserts">Desserts</option>
  </datalist>

and I'm trying to get that to show with this Javascript:

    var catVal = document.getElementsByTagName("input")[0],
    cat = document.getElementById("categories");

    catVal.style.fontSize = "1.3em";

    catVal.addEventListener("focus", function(event){
     cat.style.display = "block";
    }, false);

Any help would be appreciated,

Cheers

Body:
Question is pretty old, but it's top search on google and there are no answers to be found so I'll add it here.

To expand datalist on first click you need to set

dataListElement.style.display = "block";

and immediately hide it in next line, so it does not appear as element in your DOM, but it will only expand it under input element.

dataListElement.style.display = "none";

As of today it's not expanded on first click only in Firefox.


问:
Count Distinct XML Pattern in Notepad++ or in Linux Grep
Its a  silly question, but I can't find the answer yet.

In my XML i've got the below lines:

```<code><BLAH><BLAH><BLAH>
<ABC>123456</ABC>
<ABC>123456</ABC>
<ABC>adfadfaf</ABC>
<ABC>gdsgdhghd</ABC>
</BLAH></BLAH></BLAH>
</code>```

Distinct count of patterns in <ABC>*</ABC> is 3.

Basically I want to count unique values between <ABC> and </ABC> 3  when I do a find & count in notepad++ or in Linux grep command.

答:
This will only work if the <ABC>...</ABC> is ordered.

Ctrl+F

Find what: (<ABC>.+?</ABC>)\R(?!\1)

CHECK Match case

CHECK Wrap around

CHECK Regular expression

UNCHECK . matches newline

Count

Screenshot:

Body:
Its a  silly question, but I can't find the answer yet.

In my XML i've got the below lines:

<BLAH><BLAH><BLAH>
<ABC>123456</ABC>
<ABC>123456</ABC>
<ABC>adfadfaf</ABC>
<ABC>gdsgdhghd</ABC>
</BLAH></BLAH></BLAH>

Distinct count of patterns in <ABC>*</ABC> is 3.

Basically I want to count unique values between <ABC> and </ABC> 3  when I do a find & count in notepad++ or in Linux grep command.


问:
cv2 imread returns none when not using backslash
Hi I want to convert an image into grayscale based on alpha values but cv2 imread function returns following error:

TypeError: 'NoneType' object is not subscriptable

```<code>import cv2
import matplotlib.pyplot as plt

img = cv2.imread('C:/Users/sgunes/Downloads/Cyrillic/Ж/5a793d87b7ef9.png', cv2.IMREAD_UNCHANGED)
img_gray = 255 - img[:, :, 3]

plt.imshow(img_gray, cmap='gray', vmin=0, vmax=255)
plt.show()
</code>```

And when I debug it, my img objects gets None. How do I fix it? Thanks for your attention.

答:
According to OpenCV documentation:

The function imread loads an image from the specified file and returns it. If the image cannot be read (because of missing file, improper permissions, unsupported or invalid format), the function returns an empty matrix ( Mat::data==NULL ).

So that's mean that either you entered a wrong path, or that you don't have permissions, or that the image is not readable.

From your title, maybe it is a wrong path issue. If you want to use backslash, you can add an 'r' before your string (mean raw), or escaping each backslash (so '\' become '\\').
Note that if you use raw string (r''), you still can't finish your string by a backslash.

```<code>img = cv2.imread(r'C:\Users\sgunes\Downloads\Cyrillic\Ж\5a793d87b7ef9.png', cv2.IMREAD_UNCHANGED)
</code>```

or

img = cv2.imread('C:\\Users\\sgunes\\Downloads\\Cyrillic\\Ж\\5a793d87b7ef9.png', cv2.IMREAD_UNCHANGED)

Body:
Hi I want to convert an image into grayscale based on alpha values but cv2 imread function returns following error:

TypeError: 'NoneType' object is not subscriptable

import cv2
import matplotlib.pyplot as plt

img = cv2.imread('C:/Users/sgunes/Downloads/Cyrillic/Ж/5a793d87b7ef9.png', cv2.IMREAD_UNCHANGED)
img_gray = 255 - img[:, :, 3]

plt.imshow(img_gray, cmap='gray', vmin=0, vmax=255)
plt.show()

And when I debug it, my img objects gets None. How do I fix it? Thanks for your attention.

Body:
According to OpenCV documentation:

The function imread loads an image from the specified file and returns it. If the image cannot be read (because of missing file, improper permissions, unsupported or invalid format), the function returns an empty matrix ( Mat::data==NULL ).

So that's mean that either you entered a wrong path, or that you don't have permissions, or that the image is not readable.

From your title, maybe it is a wrong path issue. If you want to use backslash, you can add an 'r' before your string (mean raw), or escaping each backslash (so '\' become '\\').
Note that if you use raw string (r''), you still can't finish your string by a backslash.

img = cv2.imread(r'C:\Users\sgunes\Downloads\Cyrillic\Ж\5a793d87b7ef9.png', cv2.IMREAD_UNCHANGED)

or

img = cv2.imread('C:\\Users\\sgunes\\Downloads\\Cyrillic\\Ж\\5a793d87b7ef9.png', cv2.IMREAD_UNCHANGED)


问:
AWS ATHENA : HIVE_CANNOT_OPEN_SPLIT: Error opening Hive split, Schema mismatch when querying Parquet files
HIVE_CANNOT_OPEN_SPLIT: Error opening Hive split s3://exp-mahesh-sandbox/Demo/Year=2017/Month=1/Day=3/part-00015-d0e1263a-616e-435f-b4f4-9154afb3f07d.c000.snappy.parquet (offset=0, length=12795): Schema mismatch, metastore schema for row column statistical has 17 fields but parquet schema has 9 fields

I have used AWS Glue crawler to get the schema of the Parquet files. Initially I am having few files in the partition Day=1 and Day=2, run crawler and able to query it using Athena. After adding few more files in the partition Day=3, where the schema of file with "statistical"(type:struct) column has some missing fields, Athena throws the above mentioned error.
Is there any way to solve this issue. I am expecting null value in the missing fields.

I have tried UPDATE THE TABLE DEFINITION IN THE DATA CATALOG option in the crawler, but it gives the same result.

Crawler Settings

答:
You're getting that error because at least one of your Parquet files has a schema that is either different from the other files that compose the table or from the table's definition itself; it appears to be your "Day=3" partition.

This is a limitation in Athena, that requires that the files that are the data source for a table have the same schema, i.e. all the files' columns need to match Athena's table definition, even struct members.

This error happens despite the Glue crawler running successfully; the table definition is indeed updated by the crawler, but when you execute a query that touches a file with a different schema (e.g. missing a column) you get a HIVE_CANNOT_OPEN_SPLIT error.


问:
Jquery clone original HTML not DOM
I need to clone a section of markup that has already been modified in the DOM. I want to get the original HTML source - what is seen in View > Source.

clone() uses what's in the DOM

答: Try putting it in a variable before the DOM is manipulated.  I use this method for jQuery templating... var template = $('#template').html()

Title: Jquery clone original HTML not DOM


问:
Image is not showing up on my webpage
The image tag does not work. Not sure if I'm missing something or I added the image tag incorrectly. The image is in the same folder, so there's no problem in inserting the picture. </p>

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="description" content="type the content description here" />
    <meta name="keywords" content="type, keywords, here" />
    <link rel="stylesheet" href="text.css" type="text/css" />
    <style type="text/css">
    h1.align1 { text-align: center; }
    h2.align2 { text-align: center; }
    h3.align3 { text-align: center; }
    </style>
</head>
<body style="background-color: black;">
    <h1 class="align1" style="color: yellow;"><font size="8"> TEXT </h1>
    <hr style="white" />
    <h2 class="align2" style="color: red;"><font size="10"> TEXT </h2>
    <hr style="white" />
    <h3 class="align3" style="color: blue;"><font size="10"> TEXT </h3>
    <img src="years1.jpg" />
</body>
</html>
</code>```

答:
It's a img path issue. Please use a suitable file path for the image,
and also remove the font tag and use it under style.</p>

Title: Image is not showing up on my webpage

Body:
The image tag does not work. Not sure if I'm missing something or I added the image tag incorrectly. The image is in the same folder, so there's no problem in inserting the picture.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="description" content="type the content description here" />
    <meta name="keywords" content="type, keywords, here" />
    <link rel="stylesheet" href="text.css" type="text/css" />

 TEXT

 TEXT

 TEXT


问:
C++ usual arithmetic conversions not converting
First, I'd like to point out that I did read some of the other answers with generally similar titles. However, those either refer to what I assume is an older version of the standard, or deal with promotions, not conversions.

I've been crawling through "C++ Crash Course", where the author states the following in the chapter exploring built-in operators:

If none of the floating-point promotion rules apply, you then check
whether either argument is signed. If so, both operands become signed.
Finally, as with the promotion rules for floating-point types, the size of the
largest operand is used to promote the other operand: ...

If I read the standard correctly, this is not true, because, as per cppreference.com,

If both operands are signed or both are unsigned, the operand with lesser conversion rank is converted to the operand with the greater integer conversion rank

Otherwise, if the unsigned operand's conversion rank is greater or equal to the conversion rank of the signed operand, the signed operand is converted to the unsigned operand's type.

Otherwise, if the signed operand's type can represent all values of the unsigned operand, the unsigned operand is converted to the signed operand's type

Otherwise, both operands are converted to the unsigned counterpart of the signed operand's type.

What confuses me even more is the fact that the following code:

```<code>printf("Size of int is %d bytes\n", sizeof(int));
printf("Size of short is %d bytes\n", sizeof(short));
printf("Size of long is %d bytes\n", sizeof(long));
printf("Size of long long is %d bytes\n", sizeof(long long));
unsigned int x = 4000000000;
signed int y = -1;
signed long z = x + y;
printf("x + y = %ld\n", z);
</code>```

produces the following output:

```<code>Size of int is 4 bytes
Size of short is 2 bytes
Size of long is 8 bytes
Size of long long is 8 bytes
x + y = 3999999999
</code>```

As I understand the standard, y should have been converted to unsigned int, leading to an incorrect result. The result is correct, which leads me to assume that no conversion happens in this case. Why? I would be grateful for any clafirication on this matter. Thank you.

(I would also appreciate someone telling me that I won't ever need this kind of arcane knowledge in real life, even if it's not true - just for the peace of mind.)

答:
You have an addition of an unsigned int and a signed int, so same conversion rank for both operands. So the second rule will apply (emphasize mine):

[Otherwise,] if the unsigned operand's conversion rank is greater or equal to the conversion rank of the signed operand, the signed operand is converted to the unsigned operand's type.

-1 is converted to an unsigned type by adding to it the smallest power of two greater that the highest unsigned int (in fact its representation in 2's complement)

that number is added to 4000000000 and the result is the modulo of the sum and that power of two (in fact discarding its higher bit)

and you just get the expected result.

The standard mandates conversion to the unsigned type because unsigned overflow is defined by the standard, while unsigned one is not.

Body:
First, I'd like to point out that I did read some of the other answers with generally similar titles. However, those either refer to what I assume is an older version of the standard, or deal with promotions, not conversions.

I've been crawling through "C++ Crash Course", where the author states the following in the chapter exploring built-in operators:

If none of the floating-point promotion rules apply, you then check
whether either argument is signed. If so, both operands become signed.
Finally, as with the promotion rules for floating-point types, the size of the
largest operand is used to promote the other operand: ...

If I read the standard correctly, this is not true, because, as per cppreference.com,

If both operands are signed or both are unsigned, the operand with lesser conversion rank is converted to the operand with the greater integer conversion rank

Otherwise, if the unsigned operand's conversion rank is greater or equal to the conversion rank of the signed operand, the signed operand is converted to the unsigned operand's type.

Otherwise, if the signed operand's type can represent all values of the unsigned operand, the unsigned operand is converted to the signed operand's type

Otherwise, both operands are converted to the unsigned counterpart of the signed operand's type.

What confuses me even more is the fact that the following code:

printf("Size of int is %d bytes\n", sizeof(int));
printf("Size of short is %d bytes\n", sizeof(short));
printf("Size of long is %d bytes\n", sizeof(long));
printf("Size of long long is %d bytes\n", sizeof(long long));
unsigned int x = 4000000000;
signed int y = -1;
signed long z = x + y;
printf("x + y = %ld\n", z);

produces the following output:

Size of int is 4 bytes
Size of short is 2 bytes
Size of long is 8 bytes
Size of long long is 8 bytes
x + y = 3999999999

As I understand the standard, y should have been converted to unsigned int, leading to an incorrect result. The result is correct, which leads me to assume that no conversion happens in this case. Why? I would be grateful for any clafirication on this matter. Thank you.

(I would also appreciate someone telling me that I won't ever need this kind of arcane knowledge in real life, even if it's not true - just for the peace of mind.)


答:
Bootstrap has offset helper classes for this

https://getbootstrap.com/docs/4.0/layout/grid/#offsetting-columns

.col-sm-4 {
  border: 1px solid red;
}

.container {
  border: 1px solid blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />
<div class="container fluid">
  <div class="row">
    <div class="col-sm-4 offset-md-1">
      <input type="button" id="cancel" name="cancel" value="Cancel" onclick="cancel();">
    </div>
    <div class="col-sm-4 offset-md-1">
      <input type="button" id="registerX" name="registerX" value="Register" onclick="submitCheck();">
    </div>
  </div>
</div></code>```

Title: How to use multiple columns in Bootsrap not starting From column 1?

Body:
Bootstrap has offset helper classes for this

https://getbootstrap.com/docs/4.0/layout/grid/#offsetting-columns

.col-sm-4 {
  border: 1px solid red;
}

.container {
  border: 1px solid blue;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />
<div class="container fluid">
  <div class="row">
    <div class="col-sm-4 offset-md-1">
      <input type="button" id="cancel" name="cancel" value="Cancel" onclick="cancel();">
    </div>
    <div class="col-sm-4 offset-md-1">
      <input type="button" id="registerX" name="registerX" value="Register" onclick="submitCheck();">
    </div>
  </div>
</div>


问:
SmtpClient Text only version of mail body is missing apostrophe
I'm trying to send an email through the SmtpClient.

The text only part of the received email is missing all the apostrophes.

For instance, the following text (in french):

Bonjour, l’administrateur de votre organisation a validé votre demande d’accès à la plateforme.

Is received as

Bonjour, l administrateur de votre organisation a validé votre demande d accès à la plateforme.

I only have the problem with ASP.Net, the result is fine in a .NET Core 3.1 Console application.

What can be the source of this problem?

Any help appreciated.

EDIT: Here is the code

```<code>using (var smtpClient = new SmtpClient
{
          Host = @"smtp.myhost.net",
})
            {
string body = @"Bonjour, l’administrateur de votre organisation a validé votre demande d’accès à la plateforme.";
await smtpClient.SendMailAsync(
                            "noreply@mydomain.com",
                            @"dest@domain.fr",
                            string.Empty,
                            body)
                            .ConfigureAwait(continueOnCapturedContext: false);
            }
</code>```

EDIT : Problem solved by replacing the apostrophes by the ASCII versions.

答:
Consider using other overloaded function SendMailAsync(System.Net.Mail.MailMessage message) in which you can define encoding as System.Text.Encoding.UTF8for your mail message.

```<code>MailAddress to = new MailAddress("dest@domain.fr");
MailAddress from = new MailAddress("noreply@mydomain.com");
MailMessage message = new MailMessage(from, to);
message.Body = @"Bonjour, l’administrateur de votre organisation
                    a validé votre demande d’accès à la plateforme.";
message.BodyEncoding =  System.Text.Encoding.UTF8;
message.Subject = "some text";
message.SubjectEncoding = System.Text.Encoding.UTF8;
</code>```

Then SendMailAsync will be like:

```<code>await smtpClient.SendMailAsync(message)
      .ConfigureAwait(continueOnCapturedContext: false);
</code>```

Body:
I'm trying to send an email through the SmtpClient.

The text only part of the received email is missing all the apostrophes.

For instance, the following text (in french):

Bonjour, l’administrateur de votre organisation a validé votre demande d’accès à la plateforme.

Is received as

Bonjour, l administrateur de votre organisation a validé votre demande d accès à la plateforme.

I only have the problem with ASP.Net, the result is fine in a .NET Core 3.1 Console application.

What can be the source of this problem?

Any help appreciated.

EDIT: Here is the code

using (var smtpClient = new SmtpClient
{
          Host = @"smtp.myhost.net",
})
            {
string body = @"Bonjour, l’administrateur de votre organisation a validé votre demande d’accès à la plateforme.";
await smtpClient.SendMailAsync(
                            "noreply@mydomain.com",
                            @"dest@domain.fr",
                            string.Empty,
                            body)
                            .ConfigureAwait(continueOnCapturedContext: false);
            }

EDIT : Problem solved by replacing the apostrophes by the ASCII versions.

Body:
Consider using other overloaded function SendMailAsync(System.Net.Mail.MailMessage message) in which you can define encoding as System.Text.Encoding.UTF8for your mail message.

MailAddress to = new MailAddress("dest@domain.fr");
MailAddress from = new MailAddress("noreply@mydomain.com");
MailMessage message = new MailMessage(from, to);
message.Body = @"Bonjour, l’administrateur de votre organisation
                    a validé votre demande d’accès à la plateforme.";
message.BodyEncoding =  System.Text.Encoding.UTF8;
message.Subject = "some text";
message.SubjectEncoding = System.Text.Encoding.UTF8;

Then SendMailAsync will be like:

await smtpClient.SendMailAsync(message)
      .ConfigureAwait(continueOnCapturedContext: false);


问:
SQL lifting constraint of the WHERE clause on a specific result
Is there a way of using the SELECT statement in a way that one of the selected datasets ignores the WHERE condition?

```<code>SELECT employee, employee(same data, but excluded) FROM table WHERE company IN ('company1','company2') (...);
</code>```

It's intended to see total number of employees, their companies and the percentage of employees overall in the industry.

答:
Use conditional logic:</p>

```<code>SELECT something,
       (case when (conditions) then something end) as excluded_something
FROM database ;
</code>```

Body:
Is there a way of using the SELECT statement in a way that one of the selected datasets ignores the WHERE condition?

SELECT employee, employee(same data, but excluded) FROM table WHERE company IN ('company1','company2') (...);

It's intended to see total number of employees, their companies and the percentage of employees overall in the industry.

Body:
Use conditional logic:

SELECT something,
       (case when (conditions) then something end) as excluded_something
FROM database ;


问:
Keep text labels on same relative x position to the main axes for all zoom levels while maintaining an absolute y position
I want to add annotation lines to my plot with hlines() and add text labels.
I want to position the labels with a certain margin from the left axis that stays the same on all zoom levels of the plot. The y position however should move with the line.

This is my code to draw the lines:

bbox_props = dict(boxstyle='round, pad=0.3', ec='r', fc='w', alpha=1)
xmin, xmax = axis.get_xlim()
ax.hlines(pos, xmin, xmax, colors='r')
if not label is None:
    ax.text((xmax-xmin)*0.05 + xmin, pos, label, ha='left', va='center', bbox=bbox_props)
```

This is the original plot:

and after zooming in, the label moves to the right

I want that it stays at the same distance like this:

The y position behaves perfectly fine.

Is this somehow possible?

答:
You  need to position the label's x coordinate in axes coordinates, not in data coordinates,</p>

```<code>ax.text(0.05, pos, label, transform=ax.get_yaxis_transform())
</code>```

Body:
I want to add annotation lines to my plot with hlines() and add text labels.
I want to position the labels with a certain margin from the left axis that stays the same on all zoom levels of the plot. The y position however should move with the line.

This is my code to draw the lines:

bbox_props = dict(boxstyle='round, pad=0.3', ec='r', fc='w', alpha=1)
xmin, xmax = axis.get_xlim()
ax.hlines(pos, xmin, xmax, colors='r')
if not label is None:
    ax.text((xmax-xmin)*0.05 + xmin, pos, label, ha='left', va='center', bbox=bbox_props)

This is the original plot:

and after zooming in, the label moves to the right

I want that it stays at the same distance like this:

The y position behaves perfectly fine.

Is this somehow possible?

Body:
You  need to position the label's x coordinate in axes coordinates, not in data coordinates,

ax.text(0.05, pos, label, transform=ax.get_yaxis_transform())


问:
Perform an operation on multiple tables in a list
Trying to teach myself Power Query and can't get my head around this particular process.

I understand there may be other, perhaps more efficient methods of attaining the desired result, but my purpose here is to understand the process of performing multiple operations on each table in a list of tables, where the number of entries in the list is unknown and/or large.

My original data has pairs of information [Credit, Name] in adjacent columns with an unknown number of pairs.

Since it is a table, the different column/pairs have different Names.

Credit|Name|Credit1|Name1|...

If I demote the headers and transpose the table, the column headers will wind up in Column 1, and I can strip off the differentiating digit.

Using Table.Split, I can then create a number of tables where each pair of columns has the Identical headers.

I can then combine these tables to create a single, two column table, where I can Group and aggregate to get the results.

My problem is that I have not been able to figure out how to do the:

```<code>Table.PromoteHeaders(Table.Transpose(table))
</code>```

operation on each table.

This M-code produces the desired result for the four pairs of columns in the provided data, but is clearly not scalable since the number of tables needs to be known in advance.

```<code>let
   //Create the table
   Tbl1= Table.FromRecords({
      [Credit = 1, Name = "Bob", Credit2 = 2, Name2 = "Jim", Credit3 = 1, Name3 = "George", Credit4 = 1.75, Name4="Phil"],
      [Credit = 2, Name = "Phil", Credit2 = 4, Name2="George", Credit3 = 2.5, Name3 = "Stephen",Credit4 = 6, Name4="Bob"]
      }),

   //Demote headers and transpose
   transpose1 = Table.Transpose( Table.DemoteHeaders(Tbl1)),

   //Create matching names for what will eventually be the final Column Headers
    #"Split Column by Character Transition" = Table.SplitColumn(transpose1, "Column1", Splitter.SplitTextByCharacterTransition((c) => not List.Contains({"0".."9"}, c), {"0".."9"}), {"Column1.1", "Column1.2"}),
    #"Removed Columns" = Table.RemoveColumns(#"Split Column by Character Transition",{"Column1.2"}),

   //Create multiple tables from above
    multTables = Table.Split(#"Removed Columns",2),

   /*transpose and promote the headers for each table
   HOW can I do this in a single step when I don't know how many tables there might be???
   */

   tbl0 = Table.PromoteHeaders(Table.Transpose(multTables{0}),[PromoteAllScalars=true]),
   tbl1 = Table.PromoteHeaders(Table.Transpose(multTables{1}),[PromoteAllScalars=true]),
   tbl2  = Table.PromoteHeaders(Table.Transpose(multTables{2}),[PromoteAllScalars=true]),
   tbl3 = Table.PromoteHeaders(Table.Transpose(multTables{3}),[PromoteAllScalars=true]),

   combTable = Table.Combine({tbl0,tbl1,tbl2,tbl3})

in
    combTable
</code>```

Original Table

Demoted headers / Transposed table

Desired Result

Any help would be appreciated.

答:
A bit clunky but seems to work with any number of rows and any number of 2 column paired columns.

First, a bunch of indexes modified in different ways, then a filter into two table, unpivot and merge

```<code>let  Tbl1= Table.FromRecords({
  [Credit = 1, Name = "Bob", Credit2 = 2, Name2 = "Jim", Credit3 = 1, Name3 = "George", Credit4 = 1.75, Name4="Phil"],
  [Credit = 2, Name = "Phil", Credit2 = 4, Name2="George", Credit3 = 2.5, Name3 = "Stephen",Credit4 = 6, Name4="Bob"],
  [Credit = 3, Name = "Sam", Credit2 = 5, Name2="Allen", Credit3 = 3.5, Name3 = "Ralph",Credit4 = 7, Name4="Nance"]
  }),

#"Transposed Table" = Table.Transpose(Tbl1),
#"Added Index" = Table.AddIndexColumn(#"Transposed Table", "Index", 0, .5),
#"Added Custom" = Table.AddColumn(#"Added Index", "Index2", each Number.RoundDown([Index])),
#"Removed Columns" = Table.RemoveColumns(#"Added Custom",{"Index"}),
#"Added Index1" = Table.AddIndexColumn(#"Removed Columns", "Index", 0, 1),
#"Added Custom1" = Table.AddColumn(#"Added Index1", "Custom", each Number.Mod([Index],2)),
#"Removed Columns1" = Table.RemoveColumns(#"Added Custom1",{"Index"}),
#"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Removed Columns1", {"Index2", "Custom"}, "Attribute", "Value"),
#"Filtered Rows" = Table.SelectRows(#"Unpivoted Other Columns", each ([Custom] = 0)),
#"Filtered Rows2" = Table.SelectRows(#"Unpivoted Other Columns", each ([Custom] = 1)),
#"Merged Queries" = Table.NestedJoin(#"Filtered Rows2",{"Index2", "Attribute"},#"Filtered Rows",{"Index2", "Attribute"},"Filtered Rows",JoinKind.LeftOuter),
#"Expanded Filtered Rows" = Table.ExpandTableColumn(#"Merged Queries", "Filtered Rows", {"Value"}, {"Value.1"}),
#"Removed Columns2" = Table.RemoveColumns(#"Expanded Filtered Rows",{"Index2", "Custom", "Attribute"})
in #"Removed Columns2"
</code>```

Another way of doing it is to create two tables by selecting and unpivoting groups of columns based on their column names, then combining them using a custom column referring to the row index in each table

```<code>  let  Tbl1= Table.FromRecords({
  [Credit = 1, Name = "Bob", Credit2 = 2, Name2 = "Jim", Credit3 = 1, Name3 = "George", Credit4 = 1.75, Name4="Phil"],
  [Credit = 2, Name = "Phil", Credit2 = 4, Name2="George", Credit3 = 2.5, Name3 = "Stephen",Credit4 = 6, Name4="Bob"],
  [Credit = 3, Name = "Sam", Credit2 = 5, Name2="Allen", Credit3 = 3.5, Name3 = "Ralph",Credit4 = 7, Name4="Nance"]
  }),
  Credit = List.Select(Table.ColumnNames(Tbl1), each Text.Contains(_, "Credit")),
  Name = List.Select(Table.ColumnNames(Tbl1), each Text.Contains(_, "Name")),

  // create table of just Names with index
  #"Removed Columns1" = Table.RemoveColumns(Tbl1,Credit),
  #"Added Index" = Table.AddIndexColumn(#"Removed Columns1", "Index", 0, 1),
  #"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Added Index", {"Index"}, "Attribute", "Value"),

  // create table of just Credits with index
  #"Removed Columns2" = Table.RemoveColumns(Tbl1,Name),
  #"Added Index2" = Table.AddIndexColumn(#"Removed Columns2", "Index", 0, 1),
  #"Unpivoted Other Columns2" = Table.UnpivotOtherColumns(#"Added Index2", {"Index"}, "Attribute", "Value"),
  #"Added Index1" = Table.AddIndexColumn(#"Unpivoted Other Columns2", "Index.1", 0, 1),

  //merge two table together and remove excess columns
  #"Added Custom" = Table.AddColumn(#"Added Index1", "Custom", each #"Unpivoted Other Columns"{[Index.1]}[Value]),
  #"Removed Columns" = Table.RemoveColumns(#"Added Custom",{"Index", "Attribute", "Index.1"})
  in #"Removed Columns"
</code>```

Body:
Trying to teach myself Power Query and can't get my head around this particular process.

I understand there may be other, perhaps more efficient methods of attaining the desired result, but my purpose here is to understand the process of performing multiple operations on each table in a list of tables, where the number of entries in the list is unknown and/or large.

My original data has pairs of information [Credit, Name] in adjacent columns with an unknown number of pairs.

Since it is a table, the different column/pairs have different Names.

Credit|Name|Credit1|Name1|...

If I demote the headers and transpose the table, the column headers will wind up in Column 1, and I can strip off the differentiating digit.

Using Table.Split, I can then create a number of tables where each pair of columns has the Identical headers.

I can then combine these tables to create a single, two column table, where I can Group and aggregate to get the results.

My problem is that I have not been able to figure out how to do the:

Table.PromoteHeaders(Table.Transpose(table))

operation on each table.

This M-code produces the desired result for the four pairs of columns in the provided data, but is clearly not scalable since the number of tables needs to be known in advance.

let
   //Create the table
   Tbl1= Table.FromRecords({
      [Credit = 1, Name = "Bob", Credit2 = 2, Name2 = "Jim", Credit3 = 1, Name3 = "George", Credit4 = 1.75, Name4="Phil"],
      [Credit = 2, Name = "Phil", Credit2 = 4, Name2="George", Credit3 = 2.5, Name3 = "Stephen",Credit4 = 6, Name4="Bob"]
      }),

   //Demote headers and transpose
   transpose1 = Table.Transpose( Table.DemoteHeaders(Tbl1)),

   //Create matching names for what will eventually be the final Column Headers
    #"Split Column by Character Transition" = Table.SplitColumn(transpose1, "Column1", Splitter.SplitTextByCharacterTransition((c) => not List.Contains({"0".."9"}, c), {"0".."9"}), {"Column1.1", "Column1.2"}),
    #"Removed Columns" = Table.RemoveColumns(#"Split Column by Character Transition",{"Column1.2"}),

   //Create multiple tables from above
    multTables = Table.Split(#"Removed Columns",2),

   /*transpose and promote the headers for each table
   HOW can I do this in a single step when I don't know how many tables there might be???
   */

   tbl0 = Table.PromoteHeaders(Table.Transpose(multTables{0}),[PromoteAllScalars=true]),
   tbl1 = Table.PromoteHeaders(Table.Transpose(multTables{1}),[PromoteAllScalars=true]),
   tbl2  = Table.PromoteHeaders(Table.Transpose(multTables{2}),[PromoteAllScalars=true]),
   tbl3 = Table.PromoteHeaders(Table.Transpose(multTables{3}),[PromoteAllScalars=true]),

   combTable = Table.Combine({tbl0,tbl1,tbl2,tbl3})

in
    combTable

Original Table

Demoted headers / Transposed table

Desired Result

Any help would be appreciated.

Body:
A bit clunky but seems to work with any number of rows and any number of 2 column paired columns.

First, a bunch of indexes modified in different ways, then a filter into two table, unpivot and merge

let  Tbl1= Table.FromRecords({
  [Credit = 1, Name = "Bob", Credit2 = 2, Name2 = "Jim", Credit3 = 1, Name3 = "George", Credit4 = 1.75, Name4="Phil"],
  [Credit = 2, Name = "Phil", Credit2 = 4, Name2="George", Credit3 = 2.5, Name3 = "Stephen",Credit4 = 6, Name4="Bob"],
  [Credit = 3, Name = "Sam", Credit2 = 5, Name2="Allen", Credit3 = 3.5, Name3 = "Ralph",Credit4 = 7, Name4="Nance"]
  }),

#"Transposed Table" = Table.Transpose(Tbl1),
#"Added Index" = Table.AddIndexColumn(#"Transposed Table", "Index", 0, .5),
#"Added Custom" = Table.AddColumn(#"Added Index", "Index2", each Number.RoundDown([Index])),
#"Removed Columns" = Table.RemoveColumns(#"Added Custom",{"Index"}),
#"Added Index1" = Table.AddIndexColumn(#"Removed Columns", "Index", 0, 1),
#"Added Custom1" = Table.AddColumn(#"Added Index1", "Custom", each Number.Mod([Index],2)),
#"Removed Columns1" = Table.RemoveColumns(#"Added Custom1",{"Index"}),
#"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Removed Columns1", {"Index2", "Custom"}, "Attribute", "Value"),
#"Filtered Rows" = Table.SelectRows(#"Unpivoted Other Columns", each ([Custom] = 0)),
#"Filtered Rows2" = Table.SelectRows(#"Unpivoted Other Columns", each ([Custom] = 1)),
#"Merged Queries" = Table.NestedJoin(#"Filtered Rows2",{"Index2", "Attribute"},#"Filtered Rows",{"Index2", "Attribute"},"Filtered Rows",JoinKind.LeftOuter),
#"Expanded Filtered Rows" = Table.ExpandTableColumn(#"Merged Queries", "Filtered Rows", {"Value"}, {"Value.1"}),
#"Removed Columns2" = Table.RemoveColumns(#"Expanded Filtered Rows",{"Index2", "Custom", "Attribute"})
in #"Removed Columns2"

Another way of doing it is to create two tables by selecting and unpivoting groups of columns based on their column names, then combining them using a custom column referring to the row index in each table

  let  Tbl1= Table.FromRecords({
  [Credit = 1, Name = "Bob", Credit2 = 2, Name2 = "Jim", Credit3 = 1, Name3 = "George", Credit4 = 1.75, Name4="Phil"],
  [Credit = 2, Name = "Phil", Credit2 = 4, Name2="George", Credit3 = 2.5, Name3 = "Stephen",Credit4 = 6, Name4="Bob"],
  [Credit = 3, Name = "Sam", Credit2 = 5, Name2="Allen", Credit3 = 3.5, Name3 = "Ralph",Credit4 = 7, Name4="Nance"]
  }),
  Credit = List.Select(Table.ColumnNames(Tbl1), each Text.Contains(_, "Credit")),
  Name = List.Select(Table.ColumnNames(Tbl1), each Text.Contains(_, "Name")),

  // create table of just Names with index
  #"Removed Columns1" = Table.RemoveColumns(Tbl1,Credit),
  #"Added Index" = Table.AddIndexColumn(#"Removed Columns1", "Index", 0, 1),
  #"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Added Index", {"Index"}, "Attribute", "Value"),

  // create table of just Credits with index
  #"Removed Columns2" = Table.RemoveColumns(Tbl1,Name),
  #"Added Index2" = Table.AddIndexColumn(#"Removed Columns2", "Index", 0, 1),
  #"Unpivoted Other Columns2" = Table.UnpivotOtherColumns(#"Added Index2", {"Index"}, "Attribute", "Value"),
  #"Added Index1" = Table.AddIndexColumn(#"Unpivoted Other Columns2", "Index.1", 0, 1),

  //merge two table together and remove excess columns
  #"Added Custom" = Table.AddColumn(#"Added Index1", "Custom", each #"Unpivoted Other Columns"{[Index.1]}[Value]),
  #"Removed Columns" = Table.RemoveColumns(#"Added Custom",{"Index", "Attribute", "Index.1"})
  in #"Removed Columns"


问:
fastest way to see if a string is found in a file?
Let's say I have a big file. The file is a list of IPs each on a new line like this:

```<code>123.123.123.123
123.123.123.124
123.123.123.125
etc...
</code>```

I could do it like this:

```<code>$file = file_get_contents($src);
if (substr_count($file,'myip'))
    echo 'FOUND';
</code>```

Or a similar way with array style:

```<code>$file = file($src,FILE_IGNORE_NEW_LINES);
if (in_array('myip',$file))
    echo 'FOUND';
</code>```

But I think there is a third alternative that could be faster.

Parsing the file line by line and of course stopping the reading if the string is found.

Something like this:

```<code>$file = fopen($src,'r');
while(!feof($file)) {
    $ip = fgets($file);
    if ($ip == $myIP) {
        die('Found');
    }
}
fclose($file);
</code>```

My question is: do you think there are other better way?

And performance-wise which code do you think is faster?

Thanks a lot guys

答:
If you could keep the file sorted, then performing a binary search would perform well.

However, sorting the file will take some time, so if you are doing a lot of inserts/deletes it might not be very effective.

OwnerDisplayName: anon

Body:
Let's say I have a big file. The file is a list of IPs each on a new line like this:

123.123.123.123
123.123.123.124
123.123.123.125
etc...

I could do it like this:

$file = file_get_contents($src);
if (substr_count($file,'myip'))
    echo 'FOUND';

Or a similar way with array style:

$file = file($src,FILE_IGNORE_NEW_LINES);
if (in_array('myip',$file))
    echo 'FOUND';

But I think there is a third alternative that could be faster.

Parsing the file line by line and of course stopping the reading if the string is found.

Something like this:

$file = fopen($src,'r');
while(!feof($file)) {
    $ip = fgets($file);
    if ($ip == $myIP) {
        die('Found');
    }
}
fclose($file);

My question is: do you think there are other better way?

And performance-wise which code do you think is faster?

Thanks a lot guys


Title: Replace values in list if they start with certain characters using a list-comprehension

Body:
I have a following list and I am trying to replace any value which starts with 23: to 00:00:00.00

tc = ['00:00:00.360',
      '00:00:00.920',
      '00:00:00.060',
      '00:00:02.600',
      '23:59:55.680',
      '00:00:05.960',
      '00:00:01.040',
      '00:00:01.140',
      '00:00:01.060',
      '00:00:01.480',
      '00:00:00.140',
      '00:00:00.280',
      '23:59:59.800',
      '00:00:01.200',
      '00:00:00.400',
      '23:59:59.940',
      '00:00:01.220',
      '00:00:00.380']

I am able to get what I need using regex,

tc = [re.sub(r'(\b23:)(.*)',r'00:00:00.00', item) for item in tc]

and it gives me expected result as per below,

['00:00:00.360',
 '00:00:00.920',
 '00:00:00.060',
 '00:00:02.600',
 '00:00:00.00',
 '00:00:05.960',
 '00:00:01.040',
 '00:00:01.140',
 '00:00:01.060',
 '00:00:01.480',
 '00:00:00.140',
 '00:00:00.280',
 '00:00:00.00',
 '00:00:01.200',
 '00:00:00.400',
 '00:00:00.00',
 '00:00:01.220',
 '00:00:00.380']

But if I use the below method without using regex, then the result is not what I expect,

tc = [item.replace(item, '00:00:00.00') for item in tc if item.startswith('23:')]

Result:

['00:00:00.00', '00:00:00.00', '00:00:00.00']

The resultant list is only with replaced items and not the whole list. How to I use the above method to get complete list?

Body:
You need to include an else statement in the ternary operator:

>>> [item.replace(item, '00:00:00.00') if item.startswith('23:') else item for item in tc]
['00:00:00.360',
 '00:00:00.920',
 '00:00:00.060',
 '00:00:02.600',
 '00:00:00.00',
 '00:00:05.960',
 '00:00:01.040',
 '00:00:01.140',
 '00:00:01.060',
 '00:00:01.480',
 '00:00:00.140',
 '00:00:00.280',
 '00:00:00.00',
 '00:00:01.200',
 '00:00:00.400',
 '00:00:00.00',
 '00:00:01.220',
 '00:00:00.380']

Or even just:

>>> ['00:00:00.00' if item.startswith('23:') else item for item in tc]
['00:00:00.360',
 '00:00:00.920',
 '00:00:00.060',
 '00:00:02.600',
 '00:00:00.00',
 '00:00:05.960',
 '00:00:01.040',
 '00:00:01.140',
 '00:00:01.060',
 '00:00:01.480',
 '00:00:00.140',
 '00:00:00.280',
 '00:00:00.00',
 '00:00:01.200',
 '00:00:00.400',
 '00:00:00.00',
 '00:00:01.220',
 '00:00:00.380']


问:
Query Neo4j and return found Nodes with Net Driver in WPF App
I like to search in my neo4j db with a string and get all Nodes as results back to handle them later in an AutosuggestBox.

First throw was to bring up a connection and query then the db to return my Nodes.

Now Im having trouble to return each found Node with its attribute called Name if its match, im always getting strange results in my messagebaox where I try to check my returned Nodes:

```<code>        private static async Task<List<string>> GetSuggestionsFromNeoAsync(string currentInput) {

            IDriver driver = GraphDatabase.Driver("bolt://localhost:7687", AuthTokens.Basic("neo4j", "neo4j"));
            IAsyncSession session = driver.AsyncSession(o => o.WithDatabase("neo4j"));

            var query2Neo = "Match (p:Person { Name:'" + currentInput + "'}) RETURN p.samAccountName as name";

            IResultCursor cursor = await session.RunAsync(query2Neo);
            List<string> people = await cursor.ToListAsync(record => record["Name"].As<string>());

            await cursor.ConsumeAsync();

            await driver.CloseAsync();
            return people;
    }
</code>```

Ive tryed to setup that Query to get Reults like from: https://github.com/neo4j/neo4j-dotnet-driver
But most exmaples are for neo4j v3 with the Client.

thank you and best regards

update with working code:

```<code>        private static async Task ShowResultsAsync()
    {
        var found = await GetSuggestionsFromNeoAsync("Name");
        if (found.Count > 0)
        {
            //enumerate the inner list
            foreach (var item in found)
            {
                //output the actual item
                MessageBox.Show("Person found Entry: " + item);
            }
        }
        else {
            MessageBox.Show("Person not found");

        }

    }
</code>```

答:
GetSuggestionsFromNeoAsync is an asynchronous method. This mean that it will return when it hits an await and execute the remainder of the method when the Task being awaited has completed.

So when you call GetSuggestionsFromNeoAsync from your showREsults method, it runs synchronously until the IResultCursor cursor = await session.RunAsync(query2Neo) line and then returns, whereupon the MessageBox is shown. Please refer to the docs for more information about what happens in an async method.

If you want to display the MessageBox when the GetSuggestionsFromNeoAsync has completed, you should await the async method. For you to be able to do this, you need to add the async keyword to the signature of the showREsults method. You should also change its return type to Task and add the *Async suffix to its name:

```<code>private static async Task ShowResultsAsync()
{
    var found = await GetSuggestionsFromNeoAsync("Name");
    MessageBox.Show("Person found Entry: " + found.Name);
}
</code>```

Body:
I like to search in my neo4j db with a string and get all Nodes as results back to handle them later in an AutosuggestBox.

First throw was to bring up a connection and query then the db to return my Nodes.

Now Im having trouble to return each found Node with its attribute called Name if its match, im always getting strange results in my messagebaox where I try to check my returned Nodes:

        private static async Task<List<string>> GetSuggestionsFromNeoAsync(string currentInput) {

            IDriver driver = GraphDatabase.Driver("bolt://localhost:7687", AuthTokens.Basic("neo4j", "neo4j"));
            IAsyncSession session = driver.AsyncSession(o => o.WithDatabase("neo4j"));

            var query2Neo = "Match (p:Person { Name:'" + currentInput + "'}) RETURN p.samAccountName as name";

            IResultCursor cursor = await session.RunAsync(query2Neo);
            List<string> people = await cursor.ToListAsync(record => record["Name"].As<string>());

            await cursor.ConsumeAsync();

            await driver.CloseAsync();
            return people;
    }

Ive tryed to setup that Query to get Reults like from: https://github.com/neo4j/neo4j-dotnet-driver
But most exmaples are for neo4j v3 with the Client.

thank you and best regards

update with working code:

        private static async Task ShowResultsAsync()
    {
        var found = await GetSuggestionsFromNeoAsync("Name");
        if (found.Count > 0)
        {
            //enumerate the inner list
            foreach (var item in found)
            {
                //output the actual item
                MessageBox.Show("Person found Entry: " + item);
            }
        }
        else {
            MessageBox.Show("Person not found");

        }

    }

Body:
GetSuggestionsFromNeoAsync is an asynchronous method. This mean that it will return when it hits an await and execute the remainder of the method when the Task being awaited has completed.

So when you call GetSuggestionsFromNeoAsync from your showREsults method, it runs synchronously until the IResultCursor cursor = await session.RunAsync(query2Neo) line and then returns, whereupon the MessageBox is shown. Please refer to the docs for more information about what happens in an async method.

If you want to display the MessageBox when the GetSuggestionsFromNeoAsync has completed, you should await the async method. For you to be able to do this, you need to add the async keyword to the signature of the showREsults method. You should also change its return type to Task and add the *Async suffix to its name:

private static async Task ShowResultsAsync()
{
    var found = await GetSuggestionsFromNeoAsync("Name");
    MessageBox.Show("Person found Entry: " + found.Name);
}


问:
DatePicker in Kotlin showing wrong month
When implementing Datepicker in kotlin instead of July its showing M07 in all devices.

Here is code for Date Picker:

```<code>val c = Calendar.getInstance()
val year = c.get(Calendar.YEAR)
val month = c.get(Calendar.MONTH)
val day = c.get(Calendar.DAY_OF_MONTH)
val datePickerDialog = DatePickerDialog(activity, DatePickerDialog.OnDateSetListener { view, year, monthOfYear, dayOfMonth -> //differnce(dayOfMonth, monthOfYear, year, false) }, year, month, day) datePickerDialog.show()
</code>```

答:
Try replacing

{ view, year, monthOfYear, dayOfMonth -> //differnce(dayOfMonth, monthOfYear, year, false) }

With

{ view, year, monthOfYear, dayOfMonth ->
                this.year = year
                this.month = monthOfYear
                this.dayOfMonth = dayOfMonth}

Body:
When implementing Datepicker in kotlin instead of July its showing M07 in all devices.

Here is code for Date Picker:

val c = Calendar.getInstance()
val year = c.get(Calendar.YEAR)
val month = c.get(Calendar.MONTH)
val day = c.get(Calendar.DAY_OF_MONTH)
val datePickerDialog = DatePickerDialog(activity, DatePickerDialog.OnDateSetListener { view, year, monthOfYear, dayOfMonth -> //differnce(dayOfMonth, monthOfYear, year, false) }, year, month, day) datePickerDialog.show()


问:
Upload error in basic shiny app in shinyapps.io portal
A very simple shiny app with upload feature is working locally but not on shinyapps.io

Code :

```<code>ui <- shiny::fluidPage(
  fileInput("file", "Upload file")
)
server <- function(input, output){

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

Error occurring looks like this :

Link to shinyapps.io app : https://babai.shinyapps.io/stackO/

File to test on upload : http://www.mediafire.com/file/lh98smuid1mprxj/2018-05-20_02-00-10.mat/file

Have seen the following similar question ( Error deploying shiny app that uses fileInput to upload data ). But the solutions here does not work.

答:
It seems, that the problem is caused by the specific encoding, which shinyapps.io doesn't recognize.
The function fileInput() tries to read the file content immediately in order to wrap it to data.frame with the predefined structure, and it fails when unknown encoding or corrupted file is provided. From the other hand, shinyapps.io has restricted possibilities to setup environment and encoding.

So, instead I'd suggest an alternative way of reading files with readLines() function. In the below example the user has to provide URL, which is then being read into a reactive variable. The variable then can be analyzed or processed. The test URL from your example does not cause errors.

```<code>library(shiny)

ui <- shiny::fluidPage(
  fileInput("file", "Upload file"),              # FileInput (1)
  textOutput("content1"),                        # Text fragment (1)
  textInput("url", label = "Provide URL"),       # URL input (2)
  actionButton("download", label = "Read file"),
  textOutput("content2")                         # Text fragment (2)
)

server <- function(input, output) {
  reactive_val <- reactiveValues()

  # File content
  output$content1 <- renderText({
    if (is.null(input$file)) return(NULL)
    x <- readLines(input$file$datapath, n = 5, skipNul =T)
    enc2native(x)
  })

  # Read URL content
  observeEvent(input$download, {
    my_file <- input$url
    if (is.null(my_file)) return(NULL)
    file_content <- readLines(my_file, n = 5, skipNul =T)
    reactive_val[["content"]] <- enc2native(file_content)
  }, ignoreInit = T)

  # URL file content
  output$content2 <- renderText({
    if (is.null(reactive_val[["content"]])) return(NULL)
    reactive_val[["content"]]
  })
}
shinyApp(ui, server)
</code>```

Body:
A very simple shiny app with upload feature is working locally but not on shinyapps.io

Code :

ui <- shiny::fluidPage(
  fileInput("file", "Upload file")
)
server <- function(input, output){

}
shinyApp(ui, server)

Error occurring looks like this :

Link to shinyapps.io app : https://babai.shinyapps.io/stackO/

File to test on upload : http://www.mediafire.com/file/lh98smuid1mprxj/2018-05-20_02-00-10.mat/file

Have seen the following similar question ( Error deploying shiny app that uses fileInput to upload data ). But the solutions here does not work.

Body:
It seems, that the problem is caused by the specific encoding, which shinyapps.io doesn't recognize.
The function fileInput() tries to read the file content immediately in order to wrap it to data.frame with the predefined structure, and it fails when unknown encoding or corrupted file is provided. From the other hand, shinyapps.io has restricted possibilities to setup environment and encoding.

So, instead I'd suggest an alternative way of reading files with readLines() function. In the below example the user has to provide URL, which is then being read into a reactive variable. The variable then can be analyzed or processed. The test URL from your example does not cause errors.

library(shiny)

ui <- shiny::fluidPage(
  fileInput("file", "Upload file"),              # FileInput (1)
  textOutput("content1"),                        # Text fragment (1)
  textInput("url", label = "Provide URL"),       # URL input (2)
  actionButton("download", label = "Read file"),
  textOutput("content2")                         # Text fragment (2)
)

server <- function(input, output) {
  reactive_val <- reactiveValues()

  # File content
  output$content1 <- renderText({
    if (is.null(input$file)) return(NULL)
    x <- readLines(input$file$datapath, n = 5, skipNul =T)
    enc2native(x)
  })

  # Read URL content
  observeEvent(input$download, {
    my_file <- input$url
    if (is.null(my_file)) return(NULL)
    file_content <- readLines(my_file, n = 5, skipNul =T)
    reactive_val[["content"]] <- enc2native(file_content)
  }, ignoreInit = T)

  # URL file content
  output$content2 <- renderText({
    if (is.null(reactive_val[["content"]])) return(NULL)
    reactive_val[["content"]]
  })
}
shinyApp(ui, server)


问:
I need to backup views and procedures with generate scripts on sql server
I need to backup views and procedures with generate scripts on sql server

it's possible to do?

答: Yes. You can use the Microsoft SQL Server Database Publishing Wizard to generate scripts for tables, views, stored procedures and even data.</p>


问:
Which notification triggers textViewDidChange?
I believe the notification

```<code>UITextView.textDidChangeNotification
</code>```

is what triggers

```<code>textViewDidChangeSelection(_ textView: UITextView)
</code>```

to run.

However it does not trigger

```<code> textViewDidChange(_ textView: UITextView)
</code>```

to run.

In fact which is "the" notification which triggers textViewDidChange to run?

答:
I'm not sure firsthand how to answer your question, but the documentation states the following:

The text view calls this method in response to user-initiated changes to the text. This method is not called in response to programmatically initiated changes.

Implementation of this method is optional.

From here:
Text View Did Change Documentation

Body:
I believe the notification

UITextView.textDidChangeNotification

is what triggers

textViewDidChangeSelection(_ textView: UITextView)

to run.

However it does not trigger

 textViewDidChange(_ textView: UITextView)

to run.

In fact which is "the" notification which triggers textViewDidChange to run?


问:
Running a regression with shell script and make utility
I want to run a regression with a shell script which should start each test via make command. The following is a simple version of my script:

```<code>#!/bin/sh

testlist="testlist.txt"
while read line;
do
    test_name=$(echo $line | awk '{print $1}')
    program_path=$(echo $line | awk '{print $2}')
    make sim TEST_NAME=$test_name PROGRAM_PATH=$program_path
done < "$testlist"
</code>```

The problem with the above script is that when make command starts a program, the script goes to the next iteration without waiting for the completion of that program in the previous iteration and continues to read the next line from the file.

Is there any option in make utility to make sure that it waits for the completion of the program? Maybe I'm missing something else.

This is the related part of Makefile:

```<code>sim:
    vsim -i -novopt \
    -L $(QUESTA_HOME)/uvm-1.1d \
    -L questa_mvc_lib \
    -do "add wave top/AL_0/*;log -r /*" \
    -G/path=$(PROGRAM_PATH) \
    +UVM_TESTNAME=$(TEST_NAME) +UVM_VERBOSITY=UVM_MEDIUM -sv_seed random
</code>```

答:
As OP stated in a comment, he noticed that vsim forks few other processes, that are still running after vsim is finished. So he needs to wait until the other processes are finished.

I emulated your vsim command with a script that forks some sleep processes:

```<code>#!/bin/bash
forksome() {
   sleep 3&
   sleep 2&
   sleep 5&
}

echo "Forking some sleep"
forksome
</code>```

I made a Makefile, that shows your problem after make normal.

When you know which processes are forked, you can make a solution as I demonstrated with make new.

```<code>normal: sim
        ps -f

new: sim mywait
        ps -f

sim:
        ./vsim

mywait:
        echo "Waiting for process(es):"
        while pgrep sleep; do sleep 1; done
</code>```

Body:
I want to run a regression with a shell script which should start each test via make command. The following is a simple version of my script:

#!/bin/sh

testlist="testlist.txt"
while read line;
do
    test_name=$(echo $line | awk '{print $1}')
    program_path=$(echo $line | awk '{print $2}')
    make sim TEST_NAME=$test_name PROGRAM_PATH=$program_path
done < "$testlist"

The problem with the above script is that when make command starts a program, the script goes to the next iteration without waiting for the completion of that program in the previous iteration and continues to read the next line from the file.

Is there any option in make utility to make sure that it waits for the completion of the program? Maybe I'm missing something else.

This is the related part of Makefile:

sim:
    vsim -i -novopt \
    -L $(QUESTA_HOME)/uvm-1.1d \
    -L questa_mvc_lib \
    -do "add wave top/AL_0/*;log -r /*" \
    -G/path=$(PROGRAM_PATH) \
    +UVM_TESTNAME=$(TEST_NAME) +UVM_VERBOSITY=UVM_MEDIUM -sv_seed random

Body:
As OP stated in a comment, he noticed that vsim forks few other processes, that are still running after vsim is finished. So he needs to wait until the other processes are finished.

I emulated your vsim command with a script that forks some sleep processes:

#!/bin/bash
forksome() {
   sleep 3&
   sleep 2&
   sleep 5&
}

echo "Forking some sleep"
forksome

I made a Makefile, that shows your problem after make normal.

When you know which processes are forked, you can make a solution as I demonstrated with make new.

normal: sim
        ps -f

new: sim mywait
        ps -f

sim:
        ./vsim

mywait:
        echo "Waiting for process(es):"
        while pgrep sleep; do sleep 1; done


问:
Matplotlib connect scatterplot points with double headed arrow line that can be shown in mplleaflet
I have scatter plot like below:

I want to connect all blue points with the red point with a double headed arrow line that can be shown using mplleaflet.

Scatter plot shown in mplleaflet:

Below is the code:

```<code>import matplotlib.pyplot as plt
import mplleaflet
import pandas as pd
import numpy as np

def leaflet_plot_stations():

    df = pd.read_csv('C:/Users/...') #load lon and lat

    # lon= df['Branch_Lon'].tolist()
    # lat = df['Branch_Lat'].tolist()
    lon = df['Hub_Lon'].tolist()
    lat = df['Hub_lat'].tolist()
    df['demand'] = 20
    df['size'] = df['demand'].apply(lambda x: x / 20 if x > 300 else x)
    print(df)
    size = df['size'].tolist()

    fig = plt.figure()
    ax1 = fig.add_subplot(111)
    ax1.scatter(lon, lat, c='blue', alpha=0.7, s=size, label='Local Hub')
    ax1.scatter(121.222824, 28.901852, c='r', alpha=0.7, s=120, label='Gateway Hub')

    mplleaflet.show()

leaflet_plot_stations()
</code>```

答:
you can use annotate to create arrows, it's slightly easier that creating a FancyArrowPatch by hand. Then you just have to iterate through your points are set the right origin/destination

```<code>points_x, points_y = np.random.random(size=(2,25))
origin_x, origin_y = np.random.random(size=(2,))

fig, ax = plt.subplots()
ax.plot(points_x, points_y, 'o', color='blue', alpha=0.5)
ax.plot(origin_x, origin_y, 'o', color='red', alpha=0.5, ms=10)

for x,y in zip(points_x, points_y):
    ax.annotate('', xy=(origin_x, origin_y), xytext=(x,y), arrowprops=dict(arrowstyle='<|-|>'))
</code>```

Body:
I have scatter plot like below:

I want to connect all blue points with the red point with a double headed arrow line that can be shown using mplleaflet.

Scatter plot shown in mplleaflet:

Below is the code:

import matplotlib.pyplot as plt
import mplleaflet
import pandas as pd
import numpy as np

def leaflet_plot_stations():

    df = pd.read_csv('C:/Users/...') #load lon and lat

    # lon= df['Branch_Lon'].tolist()
    # lat = df['Branch_Lat'].tolist()
    lon = df['Hub_Lon'].tolist()
    lat = df['Hub_lat'].tolist()
    df['demand'] = 20
    df['size'] = df['demand'].apply(lambda x: x / 20 if x > 300 else x)
    print(df)
    size = df['size'].tolist()

    fig = plt.figure()
    ax1 = fig.add_subplot(111)
    ax1.scatter(lon, lat, c='blue', alpha=0.7, s=size, label='Local Hub')
    ax1.scatter(121.222824, 28.901852, c='r', alpha=0.7, s=120, label='Gateway Hub')

    mplleaflet.show()

leaflet_plot_stations()

Body:
you can use annotate to create arrows, it's slightly easier that creating a FancyArrowPatch by hand. Then you just have to iterate through your points are set the right origin/destination

points_x, points_y = np.random.random(size=(2,25))
origin_x, origin_y = np.random.random(size=(2,))

fig, ax = plt.subplots()
ax.plot(points_x, points_y, 'o', color='blue', alpha=0.5)
ax.plot(origin_x, origin_y, 'o', color='red', alpha=0.5, ms=10)

for x,y in zip(points_x, points_y):
    ax.annotate('', xy=(origin_x, origin_y), xytext=(x,y), arrowprops=dict(arrowstyle='<|-|>'))


问:
Python3 installed using homebrew but not updated version being used
On my Mac terminal i've installed python3 (3.7.6) using homebrew - e.g. if I issue command to upgrade via homebrew, it returns the up to date version:

```<code>$brew upgrade python3
Warning: python3 3.7.6_1 already installed
</code>```

However when I ask for the version it tells me an older version (3.4.0) is installed:

```<code>$python3 --version
Python 3.4.0
</code>```

So it's installed but not updated. I'd quite like 3.6 or later on my mac. I've tried uninstalling and reinstalling using homebrew, and had no luck. Wondering if anyone has any ideas?

//

Sidenote (1) - i'm relatively new to homebrew... $ brew doctor returns config scripts "outside your system or Homebrew directories" - not sure if this helps, and if this is the issue where to move them to.

```<code>/Library/Frameworks/Python.framework/Versions/3.4/bin/python3.4m-config
/Library/Frameworks/Python.framework/Versions/3.4/bin/python3-config
/Library/Frameworks/Python.framework/Versions/3.4/bin/python3.4-config
</code>```

Sidenote (2) - 3.7.6 isn't the newest version out, but this is the latest version that homebrew will install. Is there any way to get an even newer version?

答:
By chance i've come across the/a answer. I was editing .bash_profile and saw the very top says:

```<code># Setting PATH for Python 3.4
# The orginal version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/3.4/bin:${PATH}"
export PATH
</code>```

So I moved to this directory .../Versions/, found it had three subdirectories 3.3, 3.4, and 3.8, and updated to use:

```<code>PATH="/Library/Frameworks/Python.framework/Versions/3.8/bin:${PATH}"
</code>```

And this seems to do the trick (to use the most recent). Although interestingly i've not came across 3.7.6... but is a bit redundant in my case since I can use the newer 3.8 version.

Body:
On my Mac terminal i've installed python3 (3.7.6) using homebrew - e.g. if I issue command to upgrade via homebrew, it returns the up to date version:

$brew upgrade python3
Warning: python3 3.7.6_1 already installed

However when I ask for the version it tells me an older version (3.4.0) is installed:

$python3 --version
Python 3.4.0

So it's installed but not updated. I'd quite like 3.6 or later on my mac. I've tried uninstalling and reinstalling using homebrew, and had no luck. Wondering if anyone has any ideas?

//

Sidenote (1) - i'm relatively new to homebrew... $ brew doctor returns config scripts "outside your system or Homebrew directories" - not sure if this helps, and if this is the issue where to move them to.

/Library/Frameworks/Python.framework/Versions/3.4/bin/python3.4m-config
/Library/Frameworks/Python.framework/Versions/3.4/bin/python3-config
/Library/Frameworks/Python.framework/Versions/3.4/bin/python3.4-config

Sidenote (2) - 3.7.6 isn't the newest version out, but this is the latest version that homebrew will install. Is there any way to get an even newer version?

Body:
By chance i've come across the/a answer. I was editing .bash_profile and saw the very top says:

# Setting PATH for Python 3.4
# The orginal version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/3.4/bin:${PATH}"
export PATH

So I moved to this directory .../Versions/, found it had three subdirectories 3.3, 3.4, and 3.8, and updated to use:

PATH="/Library/Frameworks/Python.framework/Versions/3.8/bin:${PATH}"

And this seems to do the trick (to use the most recent). Although interestingly i've not came across 3.7.6... but is a bit redundant in my case since I can use the newer 3.8 version.


问:
How to point subdomain to another document root in aws
I am using AWS for the first time. I have created an ec2 instance and installed Apache server , made domain mapping from GoDaddy,

Now I want to create subdomains and  point  subdomains to the another document roots.

Like this :

```<code>www.mydomain.com should have domain root html\mydomain

www.test.mydomain.com document root to html\testsubdomain directory.

www.*.mydomain.com document root to  html\subdomain directory
                           (* any subdomain other than test)
</code>```

I tried to edit vhost file but could not find vhost file in apache server.
Generally where and how to achieve this?

Do I need to use Route53 for this?

答:
To create sub domains you need to add  entry in configuration file for each sub domain being created. You can either create new config files for each subdomain or keep adding in httpd.conf. I added in httpd.conf. the code should look like this.

```<code><VirtualHost *:80>
ServerName sub1.domain.tld
DocumentRoot "var/www/html/sub1"
</VirtualHost>

<VirtualHost *:80>
ServerName sub2.domain.tld
DocumentRoot "var/www/html/sub2"
</VirtualHost>
</code>```

This adds 2 sub domains sub1 and sub2. After this you need to create an A record in route 53 pointing to the IP of EC2 instance.

In the Name field, you can place * so that this A record would be valid for al the sub domains that will be created.

If you want the subdomain have be SSL Certified and have requested a Wildcard Certificate from ACM and attached to the EC2 instance through Eastic Load Balancer then choose "Yes" for Alias else choose "No"

Value has to be IP Address of your EC2 instance if no Alias chosen and if Alias is chosen you can provide the ELB here in this field.

Hope this helps...

Body:
I am using AWS for the first time. I have created an ec2 instance and installed Apache server , made domain mapping from GoDaddy,

Now I want to create subdomains and  point  subdomains to the another document roots.

Like this :

www.mydomain.com should have domain root html\mydomain

www.test.mydomain.com document root to html\testsubdomain directory.

www.*.mydomain.com document root to  html\subdomain directory
                           (* any subdomain other than test)

I tried to edit vhost file but could not find vhost file in apache server.
Generally where and how to achieve this?

Do I need to use Route53 for this?

Body:
To create sub domains you need to add  entry in configuration file for each sub domain being created. You can either create new config files for each subdomain or keep adding in httpd.conf. I added in httpd.conf. the code should look like this.

<VirtualHost *:80>
ServerName sub1.domain.tld
DocumentRoot "var/www/html/sub1"
</VirtualHost>

<VirtualHost *:80>
ServerName sub2.domain.tld
DocumentRoot "var/www/html/sub2"
</VirtualHost>

This adds 2 sub domains sub1 and sub2. After this you need to create an A record in route 53 pointing to the IP of EC2 instance.

In the Name field, you can place * so that this A record would be valid for al the sub domains that will be created.

If you want the subdomain have be SSL Certified and have requested a Wildcard Certificate from ACM and attached to the EC2 instance through Eastic Load Balancer then choose "Yes" for Alias else choose "No"

Value has to be IP Address of your EC2 instance if no Alias chosen and if Alias is chosen you can provide the ELB here in this field.

Hope this helps...


问:
Linq (or SQL): Get a search query and sort it order by best result
I want to create a search page for my website. The logic is the user enters some keywords and I should search those words then sort the result by best matches.
i.e:
The user enters: "MVC Microsoft WPF ASP.Net".
I want to show those results which contain most matches, such as:

Best Matches:

Learning Microsoft ASP.Net MVC

How to host a WPF form in Microsoft ASP.Net

Partial matches:

Microsoft MVC

Microsoft WPF

Microsoft ASP.Net

ASP.Net MVC

Keyword Matches:

MVC

Microsoft

WPF

ASP.Net

答:
Here's a basic strategy; it would require a stored proc:

Split your keyword string on spaces, and pad with '%'s.

For each search term, perform an insert-select to the same in-memory temp table. You'll get duplicate rows, one per record per "hit" on a search term.

Select from this temp table each distinct result, with a count of the number of times that result appears in the temp table. This is your "relevance", by which you can sort.


问:
Flutter: CustomPainter Destination image not dropping on BlendMode.src
I am trying to learn CustomPainter. I have created two rectangles successfully and trying to understand BlendMode.

As the document says when setting paintObj.blendMode = BlendMode.src, it should

Drop the destination image, only paint the source image.`

But here both destination and source painted on top of each other and not clearing destination.

This is full code:

```<code>import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(home: HomePage()));

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: SafeArea(
        child: SizedBox.expand(
          child: CustomPaint(
            painter: MyPainter(),
          ),
        ),
      ),
    );
  }
}

class MyPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paintObj = Paint();

    paintObj.color = Colors.red;
    canvas.drawRect(
      Rect.fromCircle(
        center: size.center(Offset.zero),
        radius: 40.0,
      ),
      paintObj,
    );

    paintObj.blendMode = BlendMode.src;

    paintObj.color = Colors.green;
    canvas.drawRect(
      Rect.fromCenter(
        center: size.center(Offset.zero),
        height: 160,
        width: 40,
      ),
      paintObj,
    );
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return false;
  }
}
</code>```

Result:
I don't know why the red rectangle(destination) is still drawn

What am I missing here?

答:
It seems to behave as expected.

Documentation of Paint's blendMode:

```<code>/// A blend mode to apply when a shape is drawn or a layer is composited.
///
/// The source colors are from the shape being drawn (e.g. from
/// [Canvas.drawPath]) or layer being composited (the graphics that were drawn
/// between the [Canvas.saveLayer] and [Canvas.restore] calls), after applying
/// the [colorFilter], if any.
///
/// The destination colors are from the background onto which the shape or
/// layer is being composited.
///
/// Defaults to [BlendMode.srcOver].
</code>```

Documentation of BlendMode.src:

```<code>/// Drop the destination image, only paint the source image.
///
/// Conceptually, the destination is first cleared, then the source image is
/// painted.
</code>```

I believe the destination is considered to be the rectangle below the green rectangle (of the exact same size), not the entire canvas. This would make sense as it would give CustomPainer a lot more flexibility compared to clearing the entire canvas. You should be able to test this by using semi-transparent colors. If my assumption is correct, the semi-transparent green rectangle should have uniform color because the red rectangle would be cleared from underneath it first.

Body:
I am trying to learn CustomPainter. I have created two rectangles successfully and trying to understand BlendMode.

As the document says when setting paintObj.blendMode = BlendMode.src, it should

Drop the destination image, only paint the source image.`

But here both destination and source painted on top of each other and not clearing destination.

This is full code:

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(home: HomePage()));

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: SafeArea(
        child: SizedBox.expand(
          child: CustomPaint(
            painter: MyPainter(),
          ),
        ),
      ),
    );
  }
}

class MyPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paintObj = Paint();

    paintObj.color = Colors.red;
    canvas.drawRect(
      Rect.fromCircle(
        center: size.center(Offset.zero),
        radius: 40.0,
      ),
      paintObj,
    );

    paintObj.blendMode = BlendMode.src;

    paintObj.color = Colors.green;
    canvas.drawRect(
      Rect.fromCenter(
        center: size.center(Offset.zero),
        height: 160,
        width: 40,
      ),
      paintObj,
    );
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return false;
  }
}

Result:
I don't know why the red rectangle(destination) is still drawn

What am I missing here?

Body:
It seems to behave as expected.

Documentation of Paint's blendMode:

/// A blend mode to apply when a shape is drawn or a layer is composited.
///
/// The source colors are from the shape being drawn (e.g. from
/// [Canvas.drawPath]) or layer being composited (the graphics that were drawn
/// between the [Canvas.saveLayer] and [Canvas.restore] calls), after applying
/// the [colorFilter], if any.
///
/// The destination colors are from the background onto which the shape or
/// layer is being composited.
///
/// Defaults to [BlendMode.srcOver].

Documentation of BlendMode.src:

/// Drop the destination image, only paint the source image.
///
/// Conceptually, the destination is first cleared, then the source image is
/// painted.

I believe the destination is considered to be the rectangle below the green rectangle (of the exact same size), not the entire canvas. This would make sense as it would give CustomPainer a lot more flexibility compared to clearing the entire canvas. You should be able to test this by using semi-transparent colors. If my assumption is correct, the semi-transparent green rectangle should have uniform color because the red rectangle would be cleared from underneath it first.


问:
Regex in spark.read.json
I want to read all json files which are having timestamp one hour before the current time from the hadoop directory.
File name is like test_2020021418553333

```<code>import java.util.Calendar;

import java.text.SimpleDateFormat;

val form = new SimpleDateFormat("yyyyMMddhh");

val c = Calendar.getInstance();

c.add(Calendar.HOUR, -1);

val path ="/Test_"+form.format(c.getTime())+"*";

val test_df = spark.read.json(path)

</code>```

When I run this code: Path does not exist error is coming.
Can anyone suggest how to read file names like Test_20200214{Any Possible combination of Digit}??

答:
A quick test show that you have minutes

form.format(c.getTime())
res2: String = 2020021401

So remove the latest 2 cars

regards

Title: Regex in spark.read.json

Body:
I want to read all json files which are having timestamp one hour before the current time from the hadoop directory.
File name is like test_2020021418553333

import java.util.Calendar;

import java.text.SimpleDateFormat;

val form = new SimpleDateFormat("yyyyMMddhh");

val c = Calendar.getInstance();

c.add(Calendar.HOUR, -1);

val path ="/Test_"+form.format(c.getTime())+"*";

val test_df = spark.read.json(path)

When I run this code: Path does not exist error is coming.
Can anyone suggest how to read file names like Test_20200214{Any Possible combination of Digit}??