问:
When login with other user it still picks previous user uuid from nowhere
I am working with some of my projects and the problem i am facing is when i login with user "A" and use the app for some time then i logout the user and then i login with another user "B" then in some of the screens where i have to show the user profile pic (Baseurl + profilepic name). It doesn't shows up, when i took a log of the profile pic url then i found that it still picking up the uuid of  old logged in user "A".

Note :- BaseUrl is made up with concatenation with uuid.

Here are the login and logout method classes and constant class which i am using to save the data on login response and nil the data on logout reponse

Login method if status is 1 :-

```<code>                        if(status == 1)
                        {
                            DispatchQueue.main.async {
                                GAReusableClass.sharedInstance.hideActivityIndicator()
                                UserDefaults.standard.set(self.DataDict, forKey:MaindataKey)
                                let Dict = self.mainDict[KData] as!  [String: AnyObject]
                                print("self.DataDict", self.DataDict)
                                let User_ID = Dict[KUuid]as! String
                                print(User_ID)
                                let HMACSECRETKEY = self.deviceToken + "+" + User_ID
                                kHMACKey = HMACSECRETKEY
                                let cipher:String = CryptoHelper.encrypt(input:HMACSECRETKEY)!;
                                print(HMACSECRETKEY)
                                UserDefaults.standard.setValue(cipher, forKey:HmacKey)
                                UserDefaults.standard.set(true, forKey: "isLogin")
                                GAloginUserInfo.shared.saveUserInfo(dict: Dict )
                                let tabar = self.storyboard?.instantiateViewController(withIdentifier: "GAtHomeTabbarViewController") as! GAtHomeTabbarViewController
                                self.navigationController?.pushViewController(tabar, animated: true)

                            }
</code>```

Logout method if status is 1 :-

```<code>                    if(status == 1)
                    {
                        DispatchQueue.main.async {
                            GAReusableClass.sharedInstance.hideActivityIndicator()

                            defaults.removeObject(forKey: MaindataKey)
                            defaults.removeObject(forKey: HmacKey)
                            defaults.set(false, forKey: "isLogin")
                            GAloginUserInfo.shared.removeUserInfo()

                            let login = self.storyboard?.instantiateViewController(withIdentifier: "GALoginViewController") as! GALoginViewController
                            self.navigationController?.pushViewController(login, animated: true)

                        }
</code>```

Constant class :-

```<code>import UIKit

let defaults = UserDefaults.standard
var kDeviceToken = String()
var kHMACKey = String()
let Headerkey = "header"
let KData = "data"
let KStatus = "status"
let KMessage = "message"
let MaindataKey = "MAINDATA"
let KUuid = "uuid"
let HmacKey = "HMACKEY"
let imageThumbBaseURL = "http://demodemodemo.ga/uploads/"+"\(GAloginUserInfo.shared.loginUserUuid!)"+"/video_thumbs/"
let videoFileBaseURL = "http://demodemodemo.ga/uploads/"+"\(GAloginUserInfo.shared.loginUserUuid!)"+"/video_files/"
let BaseURl = "http://demodemodemo.ga/index.php?api/"
let BaseURLProfilePic = "http://demodemodemo.ga/uploads/"+"\(GAloginUserInfo.shared.loginUserUuid!)"+"/profile_pic/"
</code>```

Login user Shared class :-

```<code>import UIKit
class GAloginUserInfo: NSObject {
    var loginUserMobileNo : String?
    var loginUserId : String?
    var loginUserUuid : String?
    var loginUserCountry : String?
    var loginUserCountryCode : String?
    var loginUserEmail : String?
    var loginUserlatitude : String?
    var loginUserLongitude : String?
    var loginUserName : String?
    var loginUserQrcode : String?
    var loginUserProfilePic : String?
    var isverify : String?
    var loginPassword : String?
    var dateOfBirth: String?
    var earnedPoints:String?
    var loginUserGender:String?
    var loginUserFollowers:Int = 0

    static let shared = GAloginUserInfo()
    func saveUserInfo (dict : [String : AnyObject?] )  {

        if let loginUserMobileNo = dict["mobile"] as? String {
            self.loginUserMobileNo = loginUserMobileNo
        }
        if let loginUserId = dict["id"] as? String {
            self.loginUserId = loginUserId
        }
        if let loginUserUuid = dict["uuid"] as? String {
            self.loginUserUuid = loginUserUuid
            print(loginUserUuid)
        }
        if let loginUserCountry = dict["countryNameCode"] as? String {
            self.loginUserCountry = loginUserCountry
        }
        if let loginUserCountryCode = dict["country_code"] as? String {
            self.loginUserCountryCode = loginUserCountryCode
        }
        if let loginUserEmail = dict["email"] as? String {
            self.loginUserEmail = loginUserEmail
        }
        if let loginUserProfilePic = dict["profile_pic"] as? String {
            self.loginUserProfilePic = loginUserProfilePic
        }
        if let loginUserLongitude = dict["logitude"] as? String {
            self.loginUserLongitude = loginUserLongitude
        }
        if let loginUserName = dict["name"] as? String {
            self.loginUserName = loginUserName
        }
        if let loginUserQrcode = dict["qr_code"] as? String {
            self.loginUserQrcode = loginUserQrcode
        }
        if let Password = dict["password"] as? String{
            self.loginPassword = Password
        }
        if let dateOfBirth = dict["dob"] as? String{
            self.dateOfBirth = dateOfBirth
        }
        if let earnedPoints = dict["points"] as? String{
            let myDouble = Double(earnedPoints)
            let doubleStr = String(format: "%.2f", myDouble!)
            self.earnedPoints = doubleStr
        }
        if let loginUserGender = dict["gender"] as? String{
            self.loginUserGender = loginUserGender
        }
        if let loginUserFollowers = dict["followersCount"] as? Int{
            self.loginUserFollowers = loginUserFollowers
        }

    }

}
extension GAloginUserInfo {
    func removeUserInfo() {
        self.loginUserMobileNo = nil
        self.loginUserId = nil
        self.loginUserUuid = nil
        self.loginUserCountry = nil
        self.loginUserCountryCode = nil
        self.loginUserEmail = nil
        self.loginUserlatitude = nil
        self.loginUserLongitude = nil
        self.loginUserName = nil
        self.loginUserQrcode = nil
        self.loginUserProfilePic = nil
        self.isverify = nil
        self.loginPassword = nil
        self.dateOfBirth = nil
        self.earnedPoints = nil
        self.loginUserGender = nil
        self.loginUserFollowers = 0
    }
}
</code>```

答:
I think when you logOut UIKit will retain some values, to remove this,
When you logout you should clear all View controller so, your all UIKit data will remove and your problem is resolved. Put this code if your logout API status is 1.

```<code>let toViewController = mainStoryboard.instantiateViewController(withIdentifier: "KSLoginViewController") as! KSLoginViewController// Login view controller here
                                    let fromView = UIApplication.shared.keyWindow!.rootViewController!.view
                                    UIApplication.shared.keyWindow?.rootViewController = toViewController

                                    let toView = toViewController.view
                                    toView?.addSubview(fromView!)

                                    UIView.animate(withDuration: 0.38, delay: 0.2, options: [], animations: {
                                        fromView?.transform = CGAffineTransform(translationX: -UIScreen.main.bounds.width, y: 0)
                                    }, completion: { finished in
                                        fromView?.removeFromSuperview()
                                    })
</code>```

After logout ,when you try to push another view controller  after logIn  use this code.

```<code>let teacher = studentStoryboard.instantiateViewController(withIdentifier: "KSStudentDashboardVC") as! KSStudentDashboardVC
                                        let aObjNavi = UINavigationController(rootViewController: teacher)
                                        let appDelegate: AppDelegate = (UIApplication.shared.delegate as? AppDelegate)!
                                        appDelegate.window?.rootViewController = aObjNavi
</code>```

Body:
I am working with some of my projects and the problem i am facing is when i login with user "A" and use the app for some time then i logout the user and then i login with another user "B" then in some of the screens where i have to show the user profile pic (Baseurl + profilepic name). It doesn't shows up, when i took a log of the profile pic url then i found that it still picking up the uuid of  old logged in user "A".

Note :- BaseUrl is made up with concatenation with uuid.

Here are the login and logout method classes and constant class which i am using to save the data on login response and nil the data on logout reponse

Login method if status is 1 :-

                        if(status == 1)
                        {
                            DispatchQueue.main.async {
                                GAReusableClass.sharedInstance.hideActivityIndicator()
                                UserDefaults.standard.set(self.DataDict, forKey:MaindataKey)
                                let Dict = self.mainDict[KData] as!  [String: AnyObject]
                                print("self.DataDict", self.DataDict)
                                let User_ID = Dict[KUuid]as! String
                                print(User_ID)
                                let HMACSECRETKEY = self.deviceToken + "+" + User_ID
                                kHMACKey = HMACSECRETKEY
                                let cipher:String = CryptoHelper.encrypt(input:HMACSECRETKEY)!;
                                print(HMACSECRETKEY)
                                UserDefaults.standard.setValue(cipher, forKey:HmacKey)
                                UserDefaults.standard.set(true, forKey: "isLogin")
                                GAloginUserInfo.shared.saveUserInfo(dict: Dict )
                                let tabar = self.storyboard?.instantiateViewController(withIdentifier: "GAtHomeTabbarViewController") as! GAtHomeTabbarViewController
                                self.navigationController?.pushViewController(tabar, animated: true)

                            }

Logout method if status is 1 :-

                    if(status == 1)
                    {
                        DispatchQueue.main.async {
                            GAReusableClass.sharedInstance.hideActivityIndicator()

                            defaults.removeObject(forKey: MaindataKey)
                            defaults.removeObject(forKey: HmacKey)
                            defaults.set(false, forKey: "isLogin")
                            GAloginUserInfo.shared.removeUserInfo()

                            let login = self.storyboard?.instantiateViewController(withIdentifier: "GALoginViewController") as! GALoginViewController
                            self.navigationController?.pushViewController(login, animated: true)

                        }

Constant class :-

import UIKit

let defaults = UserDefaults.standard
var kDeviceToken = String()
var kHMACKey = String()
let Headerkey = "header"
let KData = "data"
let KStatus = "status"
let KMessage = "message"
let MaindataKey = "MAINDATA"
let KUuid = "uuid"
let HmacKey = "HMACKEY"
let imageThumbBaseURL = "http://demodemodemo.ga/uploads/"+"\(GAloginUserInfo.shared.loginUserUuid!)"+"/video_thumbs/"
let videoFileBaseURL = "http://demodemodemo.ga/uploads/"+"\(GAloginUserInfo.shared.loginUserUuid!)"+"/video_files/"
let BaseURl = "http://demodemodemo.ga/index.php?api/"
let BaseURLProfilePic = "http://demodemodemo.ga/uploads/"+"\(GAloginUserInfo.shared.loginUserUuid!)"+"/profile_pic/"

Login user Shared class :-

import UIKit
class GAloginUserInfo: NSObject {
    var loginUserMobileNo : String?
    var loginUserId : String?
    var loginUserUuid : String?
    var loginUserCountry : String?
    var loginUserCountryCode : String?
    var loginUserEmail : String?
    var loginUserlatitude : String?
    var loginUserLongitude : String?
    var loginUserName : String?
    var loginUserQrcode : String?
    var loginUserProfilePic : String?
    var isverify : String?
    var loginPassword : String?
    var dateOfBirth: String?
    var earnedPoints:String?
    var loginUserGender:String?
    var loginUserFollowers:Int = 0

    static let shared = GAloginUserInfo()
    func saveUserInfo (dict : [String : AnyObject?] )  {

        if let loginUserMobileNo = dict["mobile"] as? String {
            self.loginUserMobileNo = loginUserMobileNo
        }
        if let loginUserId = dict["id"] as? String {
            self.loginUserId = loginUserId
        }
        if let loginUserUuid = dict["uuid"] as? String {
            self.loginUserUuid = loginUserUuid
            print(loginUserUuid)
        }
        if let loginUserCountry = dict["countryNameCode"] as? String {
            self.loginUserCountry = loginUserCountry
        }
        if let loginUserCountryCode = dict["country_code"] as? String {
            self.loginUserCountryCode = loginUserCountryCode
        }
        if let loginUserEmail = dict["email"] as? String {
            self.loginUserEmail = loginUserEmail
        }
        if let loginUserProfilePic = dict["profile_pic"] as? String {
            self.loginUserProfilePic = loginUserProfilePic
        }
        if let loginUserLongitude = dict["logitude"] as? String {
            self.loginUserLongitude = loginUserLongitude
        }
        if let loginUserName = dict["name"] as? String {
            self.loginUserName = loginUserName
        }
        if let loginUserQrcode = dict["qr_code"] as? String {
            self.loginUserQrcode = loginUserQrcode
        }
        if let Password = dict["password"] as? String{
            self.loginPassword = Password
        }
        if let dateOfBirth = dict["dob"] as? String{
            self.dateOfBirth = dateOfBirth
        }
        if let earnedPoints = dict["points"] as? String{
            let myDouble = Double(earnedPoints)
            let doubleStr = String(format: "%.2f", myDouble!)
            self.earnedPoints = doubleStr
        }
        if let loginUserGender = dict["gender"] as? String{
            self.loginUserGender = loginUserGender
        }
        if let loginUserFollowers = dict["followersCount"] as? Int{
            self.loginUserFollowers = loginUserFollowers
        }

    }

}
extension GAloginUserInfo {
    func removeUserInfo() {
        self.loginUserMobileNo = nil
        self.loginUserId = nil
        self.loginUserUuid = nil
        self.loginUserCountry = nil
        self.loginUserCountryCode = nil
        self.loginUserEmail = nil
        self.loginUserlatitude = nil
        self.loginUserLongitude = nil
        self.loginUserName = nil
        self.loginUserQrcode = nil
        self.loginUserProfilePic = nil
        self.isverify = nil
        self.loginPassword = nil
        self.dateOfBirth = nil
        self.earnedPoints = nil
        self.loginUserGender = nil
        self.loginUserFollowers = 0
    }
}

Body:
I think when you logOut UIKit will retain some values, to remove this,
When you logout you should clear all View controller so, your all UIKit data will remove and your problem is resolved. Put this code if your logout API status is 1.

let toViewController = mainStoryboard.instantiateViewController(withIdentifier: "KSLoginViewController") as! KSLoginViewController// Login view controller here
                                    let fromView = UIApplication.shared.keyWindow!.rootViewController!.view
                                    UIApplication.shared.keyWindow?.rootViewController = toViewController

                                    let toView = toViewController.view
                                    toView?.addSubview(fromView!)

                                    UIView.animate(withDuration: 0.38, delay: 0.2, options: [], animations: {
                                        fromView?.transform = CGAffineTransform(translationX: -UIScreen.main.bounds.width, y: 0)
                                    }, completion: { finished in
                                        fromView?.removeFromSuperview()
                                    })

After logout ,when you try to push another view controller  after logIn  use this code.

let teacher = studentStoryboard.instantiateViewController(withIdentifier: "KSStudentDashboardVC") as! KSStudentDashboardVC
                                        let aObjNavi = UINavigationController(rootViewController: teacher)
                                        let appDelegate: AppDelegate = (UIApplication.shared.delegate as? AppDelegate)!
                                        appDelegate.window?.rootViewController = aObjNavi


来源: stackexchange

问:
PyAudio in pycharm
I have written a program for speech to text in which I use speech recognition by pycharm ask for PyAudio so I tried to do so . But PyAudio in pycharm is not getting installed</p>

答:
Sounddevice is easier for speech recognition because of it's simplicity. However if you really need pyaudio use

```<code>pip<python version> install pyaudio #in the terminal
</code>```

if that does not work then check what python you are using in pycharm by looking at the python console tab. In this case I am using python 3.6.

```<code>import sounddevice as sd
import soundfile as sf
import speechrecognition as sr
s = sr.Recognizer()
audio = sd.rec(int(time*44100),44100)
sd.wait()
sf.write("audio.wav",audio,time*44100)
audio = sr.AudioFile("audio.wav")
with audio as file:
    audio = s.record(file)
#wit.ai is a free speech recognition api from facebook and works almost as good as google.
text = s.recognize_wit(audio, key="*********")
</code>```

ContentLicense: CC BY-SA 4.0

Title: PyAudio in pycharm

Body:
Sounddevice is easier for speech recognition because of it's simplicity. However if you really need pyaudio use

pip<python version> install pyaudio #in the terminal

if that does not work then check what python you are using in pycharm by looking at the python console tab. In this case I am using python 3.6.

import sounddevice as sd
import soundfile as sf
import speechrecognition as sr
s = sr.Recognizer()
audio = sd.rec(int(time*44100),44100)
sd.wait()
sf.write("audio.wav",audio,time*44100)
audio = sr.AudioFile("audio.wav")
with audio as file:
    audio = s.record(file)
#wit.ai is a free speech recognition api from facebook and works almost as good as google.
text = s.recognize_wit(audio, key="*********")


问:
How to create an event listener for an event raised from another class
I'm trying to create a generic listener/handler in my main form for an event raised from a class (on another file). I'm trying to do so because i need access to my form labels (and the instance of this class has to be global, so i can't declare it in my form class).

The final goal is to create DataBindings between the "Text" property of a label and a string/property, on the instance creation (which raises an event).

On my class StaticScaleDetails:

```<code>Public Class StaticScaleDetails
    Implements System.ComponentModel.INotifyPropertyChanged
    Public Event CreatedNewScale()

    Private _ipAddress As String

    Public Property ipAddress
        Get
            Return _ipAddress
        End Get
        Set(value)
            _ipAddress = value
            RaiseEvent PropertyChanged(Me, New ComponentModel.PropertyChangedEventArgs("ipAddress"))
        End Set
    End Property

    Public Event PropertyChanged(sender As Object, e As System.ComponentModel.PropertyChangedEventArgs) _
    Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged

    Public Sub New(ByVal ip As String)
        ipAddress = ip

        RaiseEvent CreatedNewScale()
    End Sub

    Public Sub AssociateHandlers(ByRef ipObject As Object)
        ipObject.DataBindings.Add(New Binding("Text", Me, "ipAddress"))
    End Sub
End Class
</code>```

I need some way from my Form class to handle the "CreatedNewScale()" event. Any ideas?

P.S.: I probably need to create a List of StaticScaleDetails instances, so i'd rather not use a handler only for a specific instance.

答:
In the end, i found the solution: i needed a list, so i created it and added only one event handler for the list object:

In a module containing some global variables, i declared

```<code>Public StaticScales As New BindingList(Of StaticScaleDetails)
</code>```

so that it could be accessed from everywhere.

I added an event handler in my Main:

```<code>Private LastIndex As Integer 'Variable to keep track of the size the list was the last time the event has been triggered

Private Sub ListIsChanged()
    If StaticScales.Count > LastIndex And StaticScales.Count <= 5 Then
        'Console.WriteLine("The list has changed: its size changed from {0} to {1}!", LastIndex, StaticScales.Count)

        SelectLabelsToAssociate()
        LastIndex = StaticScales.Count
    End If
End Sub
</code>```

And on the Load of my Main:

```<code>LastIndex = 0
AddHandler StaticScales.ListChanged, AddressOf ListIsChanged
</code>```

There are probably more "elegant" solutions (like creating a custom class which triggers the event only when an item is added instead of when the list is changed in any way), but this way it works.

Body:
I'm trying to create a generic listener/handler in my main form for an event raised from a class (on another file). I'm trying to do so because i need access to my form labels (and the instance of this class has to be global, so i can't declare it in my form class).

The final goal is to create DataBindings between the "Text" property of a label and a string/property, on the instance creation (which raises an event).

On my class StaticScaleDetails:

Public Class StaticScaleDetails
    Implements System.ComponentModel.INotifyPropertyChanged
    Public Event CreatedNewScale()

    Private _ipAddress As String

    Public Property ipAddress
        Get
            Return _ipAddress
        End Get
        Set(value)
            _ipAddress = value
            RaiseEvent PropertyChanged(Me, New ComponentModel.PropertyChangedEventArgs("ipAddress"))
        End Set
    End Property

    Public Event PropertyChanged(sender As Object, e As System.ComponentModel.PropertyChangedEventArgs) _
    Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged

    Public Sub New(ByVal ip As String)
        ipAddress = ip

        RaiseEvent CreatedNewScale()
    End Sub

    Public Sub AssociateHandlers(ByRef ipObject As Object)
        ipObject.DataBindings.Add(New Binding("Text", Me, "ipAddress"))
    End Sub
End Class

I need some way from my Form class to handle the "CreatedNewScale()" event. Any ideas?

P.S.: I probably need to create a List of StaticScaleDetails instances, so i'd rather not use a handler only for a specific instance.

Body:
In the end, i found the solution: i needed a list, so i created it and added only one event handler for the list object:

In a module containing some global variables, i declared

Public StaticScales As New BindingList(Of StaticScaleDetails)

so that it could be accessed from everywhere.

I added an event handler in my Main:

Private LastIndex As Integer 'Variable to keep track of the size the list was the last time the event has been triggered

Private Sub ListIsChanged()
    If StaticScales.Count > LastIndex And StaticScales.Count <= 5 Then
        'Console.WriteLine("The list has changed: its size changed from {0} to {1}!", LastIndex, StaticScales.Count)

        SelectLabelsToAssociate()
        LastIndex = StaticScales.Count
    End If
End Sub

And on the Load of my Main:

LastIndex = 0
AddHandler StaticScales.ListChanged, AddressOf ListIsChanged

There are probably more "elegant" solutions (like creating a custom class which triggers the event only when an item is added instead of when the list is changed in any way), but this way it works.


问:
Why iPad app build fails in xcode with a error creating temporary directory?
I'm using Xcode 4.6, and trying to run a simple app in iPad 6.1 Simulator, build fails with error message

```<code>mkdir: /Users/chakradar.r/Library/Developer/Xcode/DerivedData/dino-eddkhtnsnrlgwjgqnaceabrxcjsh/Build/Products/Debug-iphonesimulator/dino.app/wwwof: File exists
</code>```

that is a temporary directory, i even tried building it after removing the directory, it again fails with a similar message.

Once my Xcode went unresponsive so I force quit Xcode while this application was running, I suspect that could be the reason for the failure. Error message is not helping, how can I fix this situation?

答:
I too even don't know the exact root cause but

Killed both Xcode and Simulator and ran the app again and it started working for me.

ContentLicense: CC BY-SA 3.0

Body:
I'm using Xcode 4.6, and trying to run a simple app in iPad 6.1 Simulator, build fails with error message

mkdir: /Users/chakradar.r/Library/Developer/Xcode/DerivedData/dino-eddkhtnsnrlgwjgqnaceabrxcjsh/Build/Products/Debug-iphonesimulator/dino.app/wwwof: File exists

that is a temporary directory, i even tried building it after removing the directory, it again fails with a similar message.

Once my Xcode went unresponsive so I force quit Xcode while this application was running, I suspect that could be the reason for the failure. Error message is not helping, how can I fix this situation?


问:
Consume sequence of REST from same client
Currently I am consuming REST API which requires sequential call to set authentication.

//Set User

http://localhost:8081/user username

//Get Authentication

http://localhost:8081/password password

The above sequential calls are working perfectly from Browser and Postman. But when I tried to call this from Node JS using axios.get(), server was treating this 2 request as completely different request and throwing an error like "Wrong Auth Sequence".

Is that somehow we need to explicitly mention headers to say that request coming from same client? If yes please help on this.

app.get('/', (req, res) => {
    let api = `${Url}/user name ${username}`;
    console.log('api - ' + api);
    //Set Username
    axios
        .get(api)
        .then(response => {
            console.log(response);
            response.data.includes('USER SET') ? setPassword() : console.log(res.data);
        })
        .catch(err => console.log(err));
    res.send('Hello Word');
});

setPassword = () => {
    let api = `${Url}/password ${password}`;
    console.log('api - ' + api);
    axios
        .get(api)
        .then(res => {
            console.log('success: ' + res.data);
        })
        .catch(err => console.log('SetPasswordError' + err));
};```

答: The application you are trying to code for is not really a RESTful API and it is expecting you to keep the connection open for multiple requests. </p>


问:
Cant reload my React-native app on physical android device
I want to reload my react native project on my physical anroid device, I have tried the following stuff but nothing is working
There's no MENU button in my phone
-Shaking the app
-adb shell input keyevent 82
-adb shell input text "RR"

nothing happens when I type these commands

答:
Try to double tap on your phone screen, This reloads the app too.
Plus do look at this documentation, It provides all the information about how you can settle your physical device.

https://facebook.github.io/react-native/docs/running-on-device#running-your-app-on-android-devices


问:
compatibility of canvas.toBlob() in MSEdge browser
I am using canvas.toBlob() callback method to convert the image file to blob. But I see that toBlob is not compatible with microsoft edge browser.

I have tried detecting the browser and based on the browser I am using the toBlob(). For Edge we have canvas.msToBlob() and for other browsers we have canvas.toBlob(). Do we have any common method to create a blob?

```<code> let isEdgeBrowser =
 msie\s|trident\/|edge\//i.test(window.navigator.userAgent);
    if (isEdgeBrowser) {
      let blob = canvas.msToBlob();
    }

   if (!isEdgeBrowser) {
      canvas.toBlob((blob) => {
        this.fileUploadedSize = blob.size;
      });
    }
</code>```

答:
According to this article, we can see that the HTMLCanvasElement.toBlob() method not supported Edge browser, if you want to use this method in Edge browser, try to add the following polyfill:</p>

```<code>if (!HTMLCanvasElement.prototype.toBlob) {
  Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
    value: function (callback, type, quality) {
      var dataURL = this.toDataURL(type, quality).split(',')[1];
      setTimeout(function() {

        var binStr = atob( dataURL ),
            len = binStr.length,
            arr = new Uint8Array(len);

        for (var i = 0; i < len; i++ ) {
          arr[i] = binStr.charCodeAt(i);
        }

        callback( new Blob( [arr], {type: type || 'image/png'} ) );

      });
    }
  });
}
</code>```

Body:
I am using canvas.toBlob() callback method to convert the image file to blob. But I see that toBlob is not compatible with microsoft edge browser.

I have tried detecting the browser and based on the browser I am using the toBlob(). For Edge we have canvas.msToBlob() and for other browsers we have canvas.toBlob(). Do we have any common method to create a blob?

 let isEdgeBrowser =
 msie\s|trident\/|edge\//i.test(window.navigator.userAgent);
    if (isEdgeBrowser) {
      let blob = canvas.msToBlob();
    }

   if (!isEdgeBrowser) {
      canvas.toBlob((blob) => {
        this.fileUploadedSize = blob.size;
      });
    }

Body:
According to this article, we can see that the HTMLCanvasElement.toBlob() method not supported Edge browser, if you want to use this method in Edge browser, try to add the following polyfill:

if (!HTMLCanvasElement.prototype.toBlob) {
  Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
    value: function (callback, type, quality) {
      var dataURL = this.toDataURL(type, quality).split(',')[1];
      setTimeout(function() {

        var binStr = atob( dataURL ),
            len = binStr.length,
            arr = new Uint8Array(len);

        for (var i = 0; i < len; i++ ) {
          arr[i] = binStr.charCodeAt(i);
        }

        callback( new Blob( [arr], {type: type || 'image/png'} ) );

      });
    }
  });
}


问:
How can one route a search URL which has a query string embedded?
I am working on an express application and I have two GET URLs. One fetches all resources in the database but is right-protected(needs authentication and admin access) while the other fetches resources based on a search parameter(query string).

The route that requires authentication looks like so:

carRouter.get('/car', verifyToken, isAdmin, fetchAllCarAds);

This means that the admin has to be logged in first and then a check is carried out to ascertain whether he is truly an admin before he is given access. Now I have another GET route that doesn't require authentication like so
:

carRouter.get('/car?status=unsold', filterUnsoldCars);.

I understand that express does not allow routing based on query strings so how do I ensure that the request that does not require authentication(query string) is accessible in the one without query string?

答:
You can do the following things to make it work.

Check either query string exist or not inside isAdmin middleware

If query string exists, Skip validation that has been implemented inside middleware.

If query string doesn't exist, then check either user is an admin or not.


问:
CSS Height:100% issue
I'm trying to get the div wrapper to surround all the divs within it so depending on the amount of content the height of wrapper will grow.

I guessed that the way of doing this would be to set height: 100% but as you can see from the screen grab below, this is not the case.

Where it says 'No :-(' is what having height: 100% is doing where ideally I would like wrapper to be at the bottom where it says 'Yes' and I have drawn a red line.

Any help is much appreciated.

答:
Can you post a link to the css?
The first thing that comes to my mind is the position attribute of the divs inside the wrapper. If they are set to float or absolute they will not be contained in the wrapper. That is intended behavior.
i.e. Here is a nice article about containing floats:
http://complexspiral.com/publications/containing-floats/

If, as is likely, that is the problem, you can either relative-position the inside divs or, if you are using floats, you can add an invisible block-displayed hr at the end of the wrapper, like so:

```<code><div id="wrapper">
            /*All divs to be contained here*/
            <hr style="display:block;clear:left;visibility:hidden;">
</div>
</code>```

The clear:left; is what gets rid of the "floating" of the previous elements. THe 'left' should be changed according to your floats.
More in the article above, this is the method i like best.

Title: CSS Height:100% issue

Body:
Can you post a link to the css?
The first thing that comes to my mind is the position attribute of the divs inside the wrapper. If they are set to float or absolute they will not be contained in the wrapper. That is intended behavior.
i.e. Here is a nice article about containing floats:
http://complexspiral.com/publications/containing-floats/

If, as is likely, that is the problem, you can either relative-position the inside divs or, if you are using floats, you can add an invisible block-displayed hr at the end of the wrapper, like so:

<div id="wrapper">
            /*All divs to be contained here*/
            <hr style="display:block;clear:left;visibility:hidden;">
</div>

The clear:left; is what gets rid of the "floating" of the previous elements. THe 'left' should be changed according to your floats.
More in the article above, this is the method i like best.


问:
get dict every item and get a new list in one line
I have a dict,like this:

```<code>{'brand': ['Three Squirrels', 'liang', 'BE'],
  'op': ['交', '差'],
  'cate': ['aaaa','bbbb','cccc']
}
</code>```

Now, I want to make a new list,like this:

```<code> [
 {'brand':'Three Squirrels','op':'交','cate':'aaaa'},
 {'brand':'Three Squirrels','op':'差','cate':'bbbb'},
 {'brand':'liang','op':'交','cate':'aaaa'},
 {'brand':'liang','op':'交','cate':'bbbb'},
 .....
 .....
]
</code>```

list len is 3*2*3 = 18

How can I do this in one line code?

答:
You can generate all possible values via itertools.product
Then you can iterate through the values and create your list of dictionaries by zipping together keys and values

```<code>from itertools import product

dct = {'brand': ['Three Squirrels', 'liang', 'BE'],
  'op': ['交', '差'],
  'cate': ['aaaa','bbbb','cccc']
}

#Get the list of keys
keys = dct.keys()

#Iterate through the values, and zip key and value together
result = [ dict(zip(keys, item)) for item in product(*dct.values())]

print(result)
print(len(result))
</code>```

The output will be

```<code>[{'brand': 'Three Squirrels', 'op': '交', 'cate': 'aaaa'},
{'brand': 'Three Squirrels', 'op': '交', 'cate': 'bbbb'},
{'brand': 'Three Squirrels', 'op': '交', 'cate': 'cccc'},
{'brand': 'Three Squirrels', 'op': '差', 'cate': 'aaaa'},
 {'brand': 'Three Squirrels', 'op': '差', 'cate': 'bbbb'},
{'brand': 'Three Squirrels', 'op': '差', 'cate': 'cccc'},
{'brand': 'liang', 'op': '交', 'cate': 'aaaa'},
{'brand': 'liang', 'op': '交', 'cate': 'bbbb'},
{'brand': 'liang', 'op': '交', 'cate': 'cccc'},
{'brand': 'liang', 'op': '差', 'cate': 'aaaa'},
{'brand': 'liang', 'op': '差', 'cate': 'bbbb'},
{'brand': 'liang', 'op': '差', 'cate': 'cccc'},
{'brand': 'BE', 'op': '交', 'cate': 'aaaa'},
{'brand': 'BE', 'op': '交', 'cate': 'bbbb'},
{'brand': 'BE', 'op': '交', 'cate': 'cccc'},
{'brand': 'BE', 'op': '差', 'cate': 'aaaa'},
{'brand': 'BE', 'op': '差', 'cate': 'bbbb'},
{'brand': 'BE', 'op': '差', 'cate': 'cccc'}]

18
</code>```

Body:
I have a dict,like this:

{'brand': ['Three Squirrels', 'liang', 'BE'],
  'op': ['交', '差'],
  'cate': ['aaaa','bbbb','cccc']
}

Now, I want to make a new list,like this:

 [
 {'brand':'Three Squirrels','op':'交','cate':'aaaa'},
 {'brand':'Three Squirrels','op':'差','cate':'bbbb'},
 {'brand':'liang','op':'交','cate':'aaaa'},
 {'brand':'liang','op':'交','cate':'bbbb'},
 .....
 .....
]

list len is 3*2*3 = 18

How can I do this in one line code?

Body:
You can generate all possible values via itertools.product
Then you can iterate through the values and create your list of dictionaries by zipping together keys and values

from itertools import product

dct = {'brand': ['Three Squirrels', 'liang', 'BE'],
  'op': ['交', '差'],
  'cate': ['aaaa','bbbb','cccc']
}

#Get the list of keys
keys = dct.keys()

#Iterate through the values, and zip key and value together
result = [ dict(zip(keys, item)) for item in product(*dct.values())]

print(result)
print(len(result))

The output will be

[{'brand': 'Three Squirrels', 'op': '交', 'cate': 'aaaa'},
{'brand': 'Three Squirrels', 'op': '交', 'cate': 'bbbb'},
{'brand': 'Three Squirrels', 'op': '交', 'cate': 'cccc'},
{'brand': 'Three Squirrels', 'op': '差', 'cate': 'aaaa'},
 {'brand': 'Three Squirrels', 'op': '差', 'cate': 'bbbb'},
{'brand': 'Three Squirrels', 'op': '差', 'cate': 'cccc'},
{'brand': 'liang', 'op': '交', 'cate': 'aaaa'},
{'brand': 'liang', 'op': '交', 'cate': 'bbbb'},
{'brand': 'liang', 'op': '交', 'cate': 'cccc'},
{'brand': 'liang', 'op': '差', 'cate': 'aaaa'},
{'brand': 'liang', 'op': '差', 'cate': 'bbbb'},
{'brand': 'liang', 'op': '差', 'cate': 'cccc'},
{'brand': 'BE', 'op': '交', 'cate': 'aaaa'},
{'brand': 'BE', 'op': '交', 'cate': 'bbbb'},
{'brand': 'BE', 'op': '交', 'cate': 'cccc'},
{'brand': 'BE', 'op': '差', 'cate': 'aaaa'},
{'brand': 'BE', 'op': '差', 'cate': 'bbbb'},
{'brand': 'BE', 'op': '差', 'cate': 'cccc'}]

18


问:
CSS
 right of
 hover gets lost
I have a simple nested ul, the sublists are displayed right to their parent. However, if I hover other sublist elements than the first one (which is directly right to the parents list item), the hover of the parent ul is lost.  Here is a snippet where you can see the problem:

#btn {
    position: fixed;
    z-index: 5;
    top: 15px;
    left: 15px;
    cursor: pointer;
    transition: left 500ms cubic-bezier(0.6, 0.05, 0.28, 0.91);
}
#btn div {
    width: 35px;
    height: 2px;
    margin-bottom: 8px;
    background-color: #00dffc;
    transition: transform 500ms cubic-bezier(0.6, 0.05, 0.28, 0.91), opacity 500ms, background-color 250ms;
}
#btn.active {
    left: 230px;
}
#btn.active div {
    background-color: #343838;
}
#btn.active #top {
    transform: translateY(10px) rotate(-135deg);
}
#btn.active #middle {
    opacity: 0;
    transform: rotate(135deg);
}
#btn.active #bottom {
    transform: translateY(-10px) rotate(-45deg);
}
#box {
    position: fixed;
    z-index: 4;
    overflow: auto;
    top: 0px;
    left: 0px;
    width: 500px;
    opacity: 1;
    padding: 20px 0px;
    height: 100%;
    background-color: lightblue;
    color: white;
    transition: all 350ms cubic-bezier(0.6, 0.05, 0.28, 0.91);
}
#box.active {
    left: 0px;
    opacity: 1;
}
#items {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
    list-style-type: none;
    padding-left: 0;
}
#items .item {
    position: relative;
    cursor: pointer;
    font-size: 2em;
    padding: 15px 30px;
    transition: all 250ms;
}
#items .item:hover {
    padding: 15px 45px;
    background-color: rgba(52, 56, 56, 0.2);
}
#items > li > ul{
    display: none;
    top: 0px;
}
#items > li:hover > ul {
    list-style-type: none;
    margin-left: 25px;
    position: absolute;
    display: inline;
}
#items > li > ul:hover {
    list-style-type: none;
    margin-left: 25px;
    position: absolute;
    display: inline;
}
#items > li > ul > li{
    border: 1px solid;
    transition: all 250ms;
    padding: 15px 30px;

}
#items > li:hover > ul > li:hover{
    padding: 15px 45px;
    background-color: rgba(52, 56, 56, 0.2);
}
#btn, #btn * {
    will-change: transform;
}
#box {
    will-change: transform, opacity;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="box">
    <ul id="items">
            <li class="item">Item 1</li>
            <li class="item">Item 2</li>
            <li class="item">Item 3
                <ul>
                <li>Subitem 1</li>
                <li>Subitem 2</li>
                <li>Subitem 3</li>
            </ul>
            </li>
            <li class="item">Item 4
                <ul>
                <li>Subitem 1</li>
                <li>Subitem 2</li>
                <li>Subitem 3</li>
                </ul>
            </li>
            <li class="item">Item 5
                <ul>
                <li>Subitem 1</li>
                <li>Subitem 2</li>
            </ul>
            </li>
            <li class="item">Item</li>
            <li class="item">Item</li>
            <li class="item">Item</li>
    </ul>
</div></code>```

As you see, you can only hover the first subitem. Can someone help me to fix this?

答:
You can add a z-index: 1 to

```<code>#items > li > ul:hover {
    list-style-type: none;
    margin-left: 25px;
    position: absolute;
    display: inline;
    z-index: 1;
}
</code>```

#btn {
    position: fixed;
    z-index: 5;
    top: 15px;
    left: 15px;
    cursor: pointer;
    transition: left 500ms cubic-bezier(0.6, 0.05, 0.28, 0.91);
}
#btn div {
    width: 35px;
    height: 2px;
    margin-bottom: 8px;
    background-color: #00dffc;
    transition: transform 500ms cubic-bezier(0.6, 0.05, 0.28, 0.91), opacity 500ms, background-color 250ms;
}
#btn.active {
    left: 230px;
}
#btn.active div {
    background-color: #343838;
}
#btn.active #top {
    transform: translateY(10px) rotate(-135deg);
}
#btn.active #middle {
    opacity: 0;
    transform: rotate(135deg);
}
#btn.active #bottom {
    transform: translateY(-10px) rotate(-45deg);
}
#box {
    position: fixed;
    z-index: 4;
    overflow: auto;
    top: 0px;
    left: 0px;
    width: 500px;
    opacity: 1;
    padding: 20px 0px;
    height: 100%;
    background-color: lightblue;
    color: white;
    transition: all 350ms cubic-bezier(0.6, 0.05, 0.28, 0.91);
}
#box.active {
    left: 0px;
    opacity: 1;
}
#items {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
    list-style-type: none;
    padding-left: 0;
}
#items .item {
    position: relative;
    cursor: pointer;
    font-size: 2em;
    padding: 15px 30px;
    transition: all 250ms;
}
#items .item:hover {
    padding: 15px 45px;
    background-color: rgba(52, 56, 56, 0.2);
}
#items > li > ul{
    display: none;
    top: 0px;
}
#items > li:hover > ul {
    list-style-type: none;
    margin-left: 25px;
    position: absolute;
    display: inline;
}
#items > li > ul:hover {
    list-style-type: none;
    margin-left: 25px;
    position: absolute;
    display: inline;
    z-index: 1;
}
#items > li > ul > li{
    border: 1px solid;
    transition: all 250ms;
    padding: 15px 30px;

}
#items > li:hover > ul > li:hover{
    padding: 15px 45px;
    background-color: rgba(52, 56, 56, 0.2);
}
#btn, #btn * {
    will-change: transform;
}
#box {
    will-change: transform, opacity;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="box">
    <ul id="items">
            <li class="item">Item 1</li>
            <li class="item">Item 2</li>
            <li class="item">Item 3
                <ul>
                <li>Subitem 1</li>
                <li>Subitem 2</li>
                <li>Subitem 3</li>
            </ul>
            </li>
            <li class="item">Item 4
                <ul>
                <li>Subitem 1</li>
                <li>Subitem 2</li>
                <li>Subitem 3</li>
                </ul>
            </li>
            <li class="item">Item 5
                <ul>
                <li>Subitem 1</li>
                <li>Subitem 2</li>
            </ul>
            </li>
            <li class="item">Item</li>
            <li class="item">Item</li>
            <li class="item">Item</li>
    </ul>
</div></code>```

Title: CSS <ul> right of <ul> hover gets lost

Body:
I have a simple nested ul, the sublists are displayed right to their parent. However, if I hover other sublist elements than the first one (which is directly right to the parents list item), the hover of the parent ul is lost.  Here is a snippet where you can see the problem:

#btn {
    position: fixed;
    z-index: 5;
    top: 15px;
    left: 15px;
    cursor: pointer;
    transition: left 500ms cubic-bezier(0.6, 0.05, 0.28, 0.91);
}
#btn div {
    width: 35px;
    height: 2px;
    margin-bottom: 8px;
    background-color: #00dffc;
    transition: transform 500ms cubic-bezier(0.6, 0.05, 0.28, 0.91), opacity 500ms, background-color 250ms;
}
#btn.active {
    left: 230px;
}
#btn.active div {
    background-color: #343838;
}
#btn.active #top {
    transform: translateY(10px) rotate(-135deg);
}
#btn.active #middle {
    opacity: 0;
    transform: rotate(135deg);
}
#btn.active #bottom {
    transform: translateY(-10px) rotate(-45deg);
}
#box {
    position: fixed;
    z-index: 4;
    overflow: auto;
    top: 0px;
    left: 0px;
    width: 500px;
    opacity: 1;
    padding: 20px 0px;
    height: 100%;
    background-color: lightblue;
    color: white;
    transition: all 350ms cubic-bezier(0.6, 0.05, 0.28, 0.91);
}
#box.active {
    left: 0px;
    opacity: 1;
}
#items {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
    list-style-type: none;
    padding-left: 0;
}
#items .item {
    position: relative;
    cursor: pointer;
    font-size: 2em;
    padding: 15px 30px;
    transition: all 250ms;
}
#items .item:hover {
    padding: 15px 45px;
    background-color: rgba(52, 56, 56, 0.2);
}
#items > li > ul{
    display: none;
    top: 0px;
}
#items > li:hover > ul {
    list-style-type: none;
    margin-left: 25px;
    position: absolute;
    display: inline;
}
#items > li > ul:hover {
    list-style-type: none;
    margin-left: 25px;
    position: absolute;
    display: inline;
}
#items > li > ul > li{
    border: 1px solid;
    transition: all 250ms;
    padding: 15px 30px;

}
#items > li:hover > ul > li:hover{
    padding: 15px 45px;
    background-color: rgba(52, 56, 56, 0.2);
}
#btn, #btn * {
    will-change: transform;
}
#box {
    will-change: transform, opacity;
}

Item 1

Item 2

Item 3

Subitem 1

Subitem 2

Subitem 3

Item 4

Subitem 1

Subitem 2

Subitem 3

Item 5

Subitem 1

Subitem 2

Item

Item

Item

As you see, you can only hover the first subitem. Can someone help me to fix this?

Body:
You can add a z-index: 1 to

#items > li > ul:hover {
    list-style-type: none;
    margin-left: 25px;
    position: absolute;
    display: inline;
    z-index: 1;
}

#btn {
    position: fixed;
    z-index: 5;
    top: 15px;
    left: 15px;
    cursor: pointer;
    transition: left 500ms cubic-bezier(0.6, 0.05, 0.28, 0.91);
}
#btn div {
    width: 35px;
    height: 2px;
    margin-bottom: 8px;
    background-color: #00dffc;
    transition: transform 500ms cubic-bezier(0.6, 0.05, 0.28, 0.91), opacity 500ms, background-color 250ms;
}
#btn.active {
    left: 230px;
}
#btn.active div {
    background-color: #343838;
}
#btn.active #top {
    transform: translateY(10px) rotate(-135deg);
}
#btn.active #middle {
    opacity: 0;
    transform: rotate(135deg);
}
#btn.active #bottom {
    transform: translateY(-10px) rotate(-45deg);
}
#box {
    position: fixed;
    z-index: 4;
    overflow: auto;
    top: 0px;
    left: 0px;
    width: 500px;
    opacity: 1;
    padding: 20px 0px;
    height: 100%;
    background-color: lightblue;
    color: white;
    transition: all 350ms cubic-bezier(0.6, 0.05, 0.28, 0.91);
}
#box.active {
    left: 0px;
    opacity: 1;
}
#items {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
    list-style-type: none;
    padding-left: 0;
}
#items .item {
    position: relative;
    cursor: pointer;
    font-size: 2em;
    padding: 15px 30px;
    transition: all 250ms;
}
#items .item:hover {
    padding: 15px 45px;
    background-color: rgba(52, 56, 56, 0.2);
}
#items > li > ul{
    display: none;
    top: 0px;
}
#items > li:hover > ul {
    list-style-type: none;
    margin-left: 25px;
    position: absolute;
    display: inline;
}
#items > li > ul:hover {
    list-style-type: none;
    margin-left: 25px;
    position: absolute;
    display: inline;
    z-index: 1;
}
#items > li > ul > li{
    border: 1px solid;
    transition: all 250ms;
    padding: 15px 30px;

}
#items > li:hover > ul > li:hover{
    padding: 15px 45px;
    background-color: rgba(52, 56, 56, 0.2);
}
#btn, #btn * {
    will-change: transform;
}
#box {
    will-change: transform, opacity;
}

<div id="box">
    <ul id="items">
            <li class="item">Item 1</li>
            <li class="item">Item 2</li>
            <li class="item">Item 3
                <ul>
                <li>Subitem 1</li>
                <li>Subitem 2</li>
                <li>Subitem 3</li>
            </ul>
            </li>
            <li class="item">Item 4
                <ul>
                <li>Subitem 1</li>
                <li>Subitem 2</li>
                <li>Subitem 3</li>
                </ul>
            </li>
            <li class="item">Item 5
                <ul>
                <li>Subitem 1</li>
                <li>Subitem 2</li>
            </ul>
            </li>
            <li class="item">Item</li>
            <li class="item">Item</li>
            <li class="item">Item</li>
    </ul>
</div>


问:
Alternatives to Google Directions API
Which is the best alternative (if any) to the Google Directions API?

Preferrably, it should be some solution I can host, but I can consider to use an online service less restritive than Google API. These are the limits for Google Directions Business:

Google Maps API for Business customers may query up to 100,000
  directions requests per day, with up to 23 waypoints allowed in each
  request.

UPDATE

Besides these limitations, which can be negotiated with Google, I would like to have an alternative because it's a good pratice don't put all eggs in one basket :)

In the absence of somebody with a opinion strong enough to share, these two services seem to be good choices:

Here Maps

MapLink

答:
Disclosure : I work for TomTom.

Have you considered our TomTom Maps APIs.

We believe we are the best alternative for Maps APIs. To get directions you can use the Routing API's instructions type parameter :

instructionsType string.
    If specified, guidance instructions will be returned (if available). Possible values are:

coded: Returns raw instruction data without human-readable messages.

text: Returns raw instructions data with human-readable messages in plain text.

tagged: Returns raw instruction data with tagged human-readable messages to permit formatting.

You can request a free API KEY (No credit card required and no locked-in contracts) and TomTom will allow you to mix and match APIs from different providers.

Check out our tutorials for JS.

Title: Alternatives to Google Directions API


问:
How to pass data from a TableViewCell to a ContainerView?
I'm new in using Swift and need help to pass data from a TableViewCell to a ContainerView to change some text of Labels.

My current status is to passing data from a TabelViewCell to a ViewController to change the text of a Label (IBOutlet) into a second ViewController with a segue.

But I don't know how to pass data from a Cell to a ContainerView with my own ViewController.

Here is a picture of my project

Here you can find the picture of my project and problem

I just want to pass data from a TableViewCell of my "View_1" to "View_2" and change the text of the Label "Change_Text_1" in the ViewController "View_In_Container" of my ContainerView (UIView).

Perhaps you guys can help me with my problem. Thank you.

答:
When you add a ContainerView in View_2 a child view controller(View_in_container) and a segue to the child view controller are added in the storyboard. Add an identifier to the segue and pass data from View_2 prepareForSegue method. The segue from View_2 to View_in_container is performed when View_2 is loaded

```<code>class View1: UIViewController {
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "toView2", let view2 = segue.destination as? View2 {
            view2.name = "name"//Pass data from tableview data source array
        }
    }
}
class View2: UIViewController {
    var name:String?
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "toChildVC", let viewInContainer = segue.destination as? ViewInContainer {
            viewInContainer.name = self.name
        }
    }
}
class ViewInContainer: UIViewController {
    var name:String?
    override func viewDidLoad() {
        super.viewDidLoad()
        label1.text = name
    }
}
</code>```

Select the segue from View_2 to View_in_container and add an identifier toChildVC

Body:
When you add a ContainerView in View_2 a child view controller(View_in_container) and a segue to the child view controller are added in the storyboard. Add an identifier to the segue and pass data from View_2 prepareForSegue method. The segue from View_2 to View_in_container is performed when View_2 is loaded

class View1: UIViewController {
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "toView2", let view2 = segue.destination as? View2 {
            view2.name = "name"//Pass data from tableview data source array
        }
    }
}
class View2: UIViewController {
    var name:String?
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "toChildVC", let viewInContainer = segue.destination as? ViewInContainer {
            viewInContainer.name = self.name
        }
    }
}
class ViewInContainer: UIViewController {
    var name:String?
    override func viewDidLoad() {
        super.viewDidLoad()
        label1.text = name
    }
}

Select the segue from View_2 to View_in_container and add an identifier toChildVC


问:
Install electron on ubuntu
When I try to install electron on Ubuntu 15.04 using

sudo npm install electron-prebuilt -g

This is what I get

```<code>/usr/local/bin/electron -> /usr/local/lib/node_modules/electron-prebuilt/cli.js

> electron-prebuilt@0.28.3 postinstall /usr/local/lib/node_modules/electron-prebuilt
> node install.js

Downloading electron-v0.28.3-linux-x64.zip
Error: tunneling socket could not be established, cause=139936635598656:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:s23_clnt.c:795:

/usr/local/lib/node_modules/electron-prebuilt/install.js:15
  throw err
        ^
Error: tunneling socket could not be established, cause=139936635598656:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:s23_clnt.c:795:

npm WARN This failure might be due to the use of legacy binary "node"
npm WARN For further explanations, please read
/usr/share/doc/nodejs/README.Debian

npm ERR! electron-prebuilt@0.28.3 postinstall: `node install.js`
npm ERR! Exit status 8
npm ERR!
npm ERR! Failed at the electron-prebuilt@0.28.3 postinstall script.
npm ERR! This is most likely a problem with the electron-prebuilt package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node install.js
npm ERR! You can get their info via:
npm ERR!     npm owner ls electron-prebuilt
npm ERR! There is likely additional logging output above.

npm ERR! System Linux 3.19.0-18-generic
npm ERR! command "/usr/bin/nodejs" "/usr/bin/npm" "install" "-g" "electron-prebuilt"
npm ERR! cwd /usr/bin
npm ERR! node -v v0.10.25
npm ERR! npm -v 1.4.21
npm ERR! code ELIFECYCLE
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     /usr/bin/npm-debug.log
npm ERR! not ok code 0
</code>```

I tried

Creating a system link for node with the command:
ln -s node nodejs in the /usr/bin/ folder

and

installing node-legacy package: sudo apt-get install node-legacy
as suggested here
with no luck.

Couldn't find anything more on other forums.So please help.
Thanks in advance.

答:
I reached here because my final app wasn't installing on ubuntu.
In case someone has the same problem go to the build location and run from terminal using :
sudo dpkg -i <name of your install/build file>
p.s. I didn't find this solution anywhere else which is why I'm posting it here

Title: Install electron on ubuntu

Body:
When I try to install electron on Ubuntu 15.04 using

sudo npm install electron-prebuilt -g

This is what I get

/usr/local/bin/electron -> /usr/local/lib/node_modules/electron-prebuilt/cli.js

> electron-prebuilt@0.28.3 postinstall /usr/local/lib/node_modules/electron-prebuilt
> node install.js

Downloading electron-v0.28.3-linux-x64.zip
Error: tunneling socket could not be established, cause=139936635598656:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:s23_clnt.c:795:

/usr/local/lib/node_modules/electron-prebuilt/install.js:15
  throw err
        ^
Error: tunneling socket could not be established, cause=139936635598656:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:s23_clnt.c:795:

npm WARN This failure might be due to the use of legacy binary "node"
npm WARN For further explanations, please read
/usr/share/doc/nodejs/README.Debian

npm ERR! electron-prebuilt@0.28.3 postinstall: `node install.js`
npm ERR! Exit status 8
npm ERR!
npm ERR! Failed at the electron-prebuilt@0.28.3 postinstall script.
npm ERR! This is most likely a problem with the electron-prebuilt package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node install.js
npm ERR! You can get their info via:
npm ERR!     npm owner ls electron-prebuilt
npm ERR! There is likely additional logging output above.

npm ERR! System Linux 3.19.0-18-generic
npm ERR! command "/usr/bin/nodejs" "/usr/bin/npm" "install" "-g" "electron-prebuilt"
npm ERR! cwd /usr/bin
npm ERR! node -v v0.10.25
npm ERR! npm -v 1.4.21
npm ERR! code ELIFECYCLE
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     /usr/bin/npm-debug.log
npm ERR! not ok code 0

I tried

Creating a system link for node with the command:
ln -s node nodejs in the /usr/bin/ folder

and

installing node-legacy package: sudo apt-get install node-legacy
as suggested here
with no luck.

Couldn't find anything more on other forums.So please help.
Thanks in advance.


问:
How to use in Terraform resources already in AWS (created manually)?
Is there a way to use in my terraform resources that already exist in my AWS account, which were created manually? I don't want to change them, and honestly, I don't want to "touch" them. I just need some of those resources for the environment I'm creating.
For example, vpc and IAM.

I have read a bit about import, but I am not sure that it is the answer?

答:
Terraform has 2 ways of using resources that exist outside of the context or directory it's being applied on.

The first is data sources which allow you to look up existing resources and pass information about them to other resources. The aws_ami data source documentation provides this useful example:

```<code>data "aws_ami" "ubuntu" {
  most_recent = true

  filter {
    name   = "name"
    values = ["ubuntu/images/hvm-ssd/ubuntu-trusty-14.04-amd64-server-*"]
  }

  filter {
    name   = "virtualization-type"
    values = ["hvm"]
  }

  owners = ["099720109477"] # Canonical
}

resource "aws_instance" "web" {
  ami           = "${data.aws_ami.ubuntu.id}"
  instance_type = "t2.micro"

  tags = {
    Name = "HelloWorld"
  }
}
</code>```

This allows Terraform to go and fetch the existing AMI that matches the criteria specified in the data source, selects the most recent AMI and then passes the AMI's ID to the aws_instance resource so that it will be built from that AMI.

Even if you are creating all of your resources with Terraform this can still be useful as it allows you to split up your Terraform configuration to limit blast radius and control what things are updated at the same time while still allowing you to access information about those resources. The aws_subnet_ids documentation has an example that provides a good example of this where the subnets may have been created by Terraform in a different context or directory to the instances you want to create:

```<code>data "aws_subnet_ids" "private" {
  vpc_id = "${var.vpc_id}"

  tags = {
    Tier = "Private"
  }
}

resource "aws_instance" "app" {
  count         = "3"
  ami           = "${var.ami}"
  instance_type = "t2.micro"
  subnet_id     = "${element(data.aws_subnet_ids.private.ids, count.index)}"
}
</code>```

The second way of using existing resources is to import them into the state. This allows Terraform to begin managing existing resources as if Terraform had originally created them. As such, any changes made to the Terraform configuration will then be applied to the existing resource when you next run terraform apply. It also means that if you ran terraform destroy then the resource would be removed.

Body:
Terraform has 2 ways of using resources that exist outside of the context or directory it's being applied on.

The first is data sources which allow you to look up existing resources and pass information about them to other resources. The aws_ami data source documentation provides this useful example:

data "aws_ami" "ubuntu" {
  most_recent = true

  filter {
    name   = "name"
    values = ["ubuntu/images/hvm-ssd/ubuntu-trusty-14.04-amd64-server-*"]
  }

  filter {
    name   = "virtualization-type"
    values = ["hvm"]
  }

  owners = ["099720109477"] # Canonical
}

resource "aws_instance" "web" {
  ami           = "${data.aws_ami.ubuntu.id}"
  instance_type = "t2.micro"

  tags = {
    Name = "HelloWorld"
  }
}

This allows Terraform to go and fetch the existing AMI that matches the criteria specified in the data source, selects the most recent AMI and then passes the AMI's ID to the aws_instance resource so that it will be built from that AMI.

Even if you are creating all of your resources with Terraform this can still be useful as it allows you to split up your Terraform configuration to limit blast radius and control what things are updated at the same time while still allowing you to access information about those resources. The aws_subnet_ids documentation has an example that provides a good example of this where the subnets may have been created by Terraform in a different context or directory to the instances you want to create:

data "aws_subnet_ids" "private" {
  vpc_id = "${var.vpc_id}"

  tags = {
    Tier = "Private"
  }
}

resource "aws_instance" "app" {
  count         = "3"
  ami           = "${var.ami}"
  instance_type = "t2.micro"
  subnet_id     = "${element(data.aws_subnet_ids.private.ids, count.index)}"
}

The second way of using existing resources is to import them into the state. This allows Terraform to begin managing existing resources as if Terraform had originally created them. As such, any changes made to the Terraform configuration will then be applied to the existing resource when you next run terraform apply. It also means that if you ran terraform destroy then the resource would be removed.


问:
Cannot start Concurrency Visualizer in Visual Studio 2012. Got error "Unable to start the ETW collection"
When I tried to profile a WPF application with Concurrency Visualzer (tried both launch and attach to process), I got the following error pop up - "Unable to start the ETW collection"

ETW clearly means "Event Tracing for Windows", but I don't understand why VS cannot start it during profiling session. Thanks for the help.

答:
For anyone else running into this without access to tracelog.exe (which does not appear to be included in WDK 10).

List all Data Collector Sets:

```<code>logman -ets
</code>```

For me the perpetrator was NT Kernel Logger which was stopped by

```<code>logman stop "NT Kernel Logger" -ets
</code>```

Body:
For anyone else running into this without access to tracelog.exe (which does not appear to be included in WDK 10).

List all Data Collector Sets:

logman -ets

For me the perpetrator was NT Kernel Logger which was stopped by

logman stop "NT Kernel Logger" -ets


问:
Greying out certain parts of html until a radio button is checked
I have a weird request i havent had before and im not sure how to go about it.

Basically i have an online application form, each question is contained in its own div, at first i want the first div shown and the rest of the questions to be 'greyed' out, then when someone clicks a radio button for the first question, the second question then ungreys itself and so on.

The code for the HTML i have so far is below, i was wondering if someone could help me out with this.

```<code><div class="line">
    <label><span>1.</span>This is a first question?</label>
    <div class="right-box small">
        <input type="radio" name="" value=""><label style="padding-left: 3px; padding-right: 24px;">No</label><input type="radio" name="" value=""><label style="padding-left: 3px;">Yes</label>
    </div>
</div>
<div class="line">
    <label><span>2.</span>This is a second question?</label>
    <div class="right-box small">
        <input type="radio" name="" value=""><label style="padding-left: 3px; padding-right: 24px;">No</label><input type="radio" name="" value=""><label style="padding-left: 3px;">Yes</label>
    </div>
</div>

<div class="line">
    <label><span>3.</span>This is a third question?</label>
    <div class="right-box small">
        <input type="radio" name="" value=""><label style="padding-left: 3px; padding-right: 24px;">No</label><input type="radio" name="" value=""><label style="padding-left: 3px;">Yes</label>
    </div>
</div>
</code>```

答:
You can also use opacity to create a "greying out" effect.</p>

```<code>$(document).ready(function() {
    //grey out all lines.
    $(".line").css({opacity:'0.2'});
    $(".line input").attr("disabled", "disabled");

    //add input change handlers
    $(".line input").change(function() {
        //enable the next line
        $(this).parents(".line").next(".line").css({opacity:'1'});
        $(this).parents(".line").next(".line").find("input").attr("disabled", "");
    });

    //enable the first line
    $(".line:first").css({opacity:'1'});
    $(".line:first input").attr("disabled", "");
});
</code>```

Body:
I have a weird request i havent had before and im not sure how to go about it.

Basically i have an online application form, each question is contained in its own div, at first i want the first div shown and the rest of the questions to be 'greyed' out, then when someone clicks a radio button for the first question, the second question then ungreys itself and so on.

The code for the HTML i have so far is below, i was wondering if someone could help me out with this.

    1.This is a first question?

        <input type="radio" name="" value="">No<input type="radio" name="" value="">Yes

    2.This is a second question?

        <input type="radio" name="" value="">No<input type="radio" name="" value="">Yes

    3.This is a third question?

        <input type="radio" name="" value="">No<input type="radio" name="" value="">Yes

Body:
You can also use opacity to create a "greying out" effect.

$(document).ready(function() {
    //grey out all lines.
    $(".line").css({opacity:'0.2'});
    $(".line input").attr("disabled", "disabled");

    //add input change handlers
    $(".line input").change(function() {
        //enable the next line
        $(this).parents(".line").next(".line").css({opacity:'1'});
        $(this).parents(".line").next(".line").find("input").attr("disabled", "");
    });

    //enable the first line
    $(".line:first").css({opacity:'1'});
    $(".line:first input").attr("disabled", "");
});


问:
How to offline video content using PWA?
I have few questions on PWA offline videos.

How can I offline the video using the Progressive Web App?

Which storage mechanism should I use to store video data on the client side?

Is there any storage limit browser-wise?

I did offline functionality with text data using PWA using service workers. But stuck in how to do same with video.

Any help will be appreciable.

答:
this is helpful repository

PWA download video manager use local database PouchDB

you can download video and store video Blob data in local Database and Use that offline

https://github.com/mohammadnazari110/pwa_offline_video_download

Title: How to offline video content using PWA?


问:
std::condition_variable spurious blocking
As you know, condition variables should be called in cycle to avoid spurious wake-ups. Like this:

```<code>while (not condition)
    condvar.wait();
</code>```

If another thread wants to wake up waiting thread, it must set condition flag to true. E.g.:

```<code>condition = true;
condvar.notify_one();
</code>```

I wonder, is it possible for condition variable to be blocked by this scenario:

1)Waiting thread checks condition flag, and finds it is equal to FALSE, so, it's going to enter condvar.wait() routine.

2)But just before this (but after condition flag checking) waiting thread is preempted by kernel (e.g. because of time slot expiration).

3) At this time, another thread wants to notify waiting thread about condition. It sets condition flag to TRUE and calls condvar.notify_one();

4) When kernel scheduler runs first thread again, it enters condvar.wait() routine, but the notification have been already missed.

So, waiting thread can't exit from condvar.wait(), despite condition flag is set to TRUE, because there is no wake up notifications anymore.

Is it possible?

答:
Mike Seymour his answer is incomplete because there is a race condition which ends up with wakeup lost.
The right way is to (now with the c++11) is as follow:

Thread1:

```<code>std::unique_lock<std::mutex> lck(myMutex);
condvar.wait(lck, []{ return condition; }); // prevent spurious wakeup
// Process data
</code>```

Thread2:

```<code>{
    std::lock_guard<std::mutex> lck(myMutex);
    condition = true;
} // unlock here! prevent wakeup lost
condvar.notify_one();
</code>```

Body:
As you know, condition variables should be called in cycle to avoid spurious wake-ups. Like this:

while (not condition)
    condvar.wait();

If another thread wants to wake up waiting thread, it must set condition flag to true. E.g.:

condition = true;
condvar.notify_one();

I wonder, is it possible for condition variable to be blocked by this scenario:

1)Waiting thread checks condition flag, and finds it is equal to FALSE, so, it's going to enter condvar.wait() routine.

2)But just before this (but after condition flag checking) waiting thread is preempted by kernel (e.g. because of time slot expiration).

3) At this time, another thread wants to notify waiting thread about condition. It sets condition flag to TRUE and calls condvar.notify_one();

4) When kernel scheduler runs first thread again, it enters condvar.wait() routine, but the notification have been already missed.

So, waiting thread can't exit from condvar.wait(), despite condition flag is set to TRUE, because there is no wake up notifications anymore.

Is it possible?

Body:
Mike Seymour his answer is incomplete because there is a race condition which ends up with wakeup lost.
The right way is to (now with the c++11) is as follow:

Thread1:

std::unique_lock<std::mutex> lck(myMutex);
condvar.wait(lck, []{ return condition; }); // prevent spurious wakeup
// Process data

Thread2:

{
    std::lock_guard<std::mutex> lck(myMutex);
    condition = true;
} // unlock here! prevent wakeup lost
condvar.notify_one();


问:
Woocommerce product categories are missing (not displaying) when adding product
I have recently come across a problem where i can't assign products to categories as the categories aren't displaying in the meta box when adding products. Here is the example:

Once i add the new category it seems to disappear when the page is reloaded. You can see that it says 6 items but it doesn't show any categories. Here is an example:

答: I had this same issue after updating to WooCommerce 3.6. Solved it by deactivating the WP Term Images plugin.</p>


问:
How to debug Lua remotely?
I'm searching for the best way to debug Lua remotely, ( like from a web browser ).

I saw RemDebug, but the last project update was done on 2006. It works with Lua 5.0 and 5.1, but Lua 5.2 is quite close, and I don't see RemDebug to get an update anytime soon.

I could mount a small embedded web-server on my debug host, and use something like RemDebug to communicate with it, and perform remote debugging via HTTP.

Suggestions are appreciated.

答: I found Hillin's Remote Lua Debugger 1.2.0.218</p>

ContentLicense: CC BY-SA 2.5

Title: How to debug Lua remotely?


问:
set vaadin-combo-box label and value properly in polymer
i try to implements this example this into polymer since i need to display label's into input.

i just tried

html :

        <form id="formC">

   <iron-ajax url="/url" last-response="{{resp}}" auto></iron-ajax>

   <vaadin-combo-box id="Box" name="Box" selected-item="{{label}}"
   placeholder="Please select" items="[[resp]]" item-value-path="label"
   item-label-path="label" value$='[[data.label]]' name='label' >
   </vaadin-combo-box>

      <input size="8" name="valu" value$='[[data.valu]]'>

        </form>

```

<ol start="2">
<li>script</li>
</ol>

<pre class="lang-js prettyprint-override"><code>        ready(){
            const combobox = Polymer.dom(this.root).querySelector('vaadin-combo-
     box');
            combobox.items = [
    {label: 'One', nilai: 1},
    {label: 'Two', nilai: 2},
    {label: 'Three', nilai: 3}
  ];
        combobox.addEventListener('selected-item-changed', function() {
         alert("selected-item-change" + JSON.stringify(combobox.selectedItem));
        });
         combobox.addEventListener('value-changed', function() {
         alert("value-change" + combobox.nilai );
        });
        }

</code>```

on combobox addEventListener there's an error Uncaught TypeError: Cannot read property 'addEventListener' of null but the error is from queryselector

update 1. : querySelector success with Polymer.dom(this.root).querySelector

update 2. : still not understood why combobox.nilai 'undifined'

update 3. : it works combobox.selectedItem.nilai ^^ thx god, thx everyone .. now i just need to inject the value

答:
Does hmtl mentioned above located under a<template>? In other words, are you creating a Shadow DOM?

If so, by document.querySelector('vaadin-combo-box');  you are looking for combobox in the "light" DOM and apparently there is no combobox there, so null is returned. Consequentially, the error is thrown, when you try to add a listner to null

But otherwise, what is a component with the comp id? You would need to access your combobox in the same way.

There are discussions on similar topic here:

Polymer: How to add event listeners to custom polymer element under conditional template

Polymer automatic node finding with dynamic id value

How to query elements within shadow DOM from outside in Dart?

Github : this.$ vs. this.shadowRoot.querySelector

Also, examples from official documentation might be helpful : Handle and fire events

Body:
i try to implements this example this into polymer since i need to display label's into input.

i just tried

html :

        <form id="formC">

   <iron-ajax url="/url" last-response="{{resp}}" auto></iron-ajax>

   <vaadin-combo-box id="Box" name="Box" selected-item="{{label}}"
   placeholder="Please select" items="[[resp]]" item-value-path="label"
   item-label-path="label" value$='[[data.label]]' name='label' >
   </vaadin-combo-box>

      <input size="8" name="valu" value$='[[data.valu]]'>

        </form>

script

        ready(){
            const combobox = Polymer.dom(this.root).querySelector('vaadin-combo-
     box');
            combobox.items = [
    {label: 'One', nilai: 1},
    {label: 'Two', nilai: 2},
    {label: 'Three', nilai: 3}
  ];
        combobox.addEventListener('selected-item-changed', function() {
         alert("selected-item-change" + JSON.stringify(combobox.selectedItem));
        });
         combobox.addEventListener('value-changed', function() {
         alert("value-change" + combobox.nilai );
        });
        }

on combobox addEventListener there's an error Uncaught TypeError: Cannot read property 'addEventListener' of null but the error is from queryselector

update 1. : querySelector success with Polymer.dom(this.root).querySelector

update 2. : still not understood why combobox.nilai 'undifined'

update 3. : it works combobox.selectedItem.nilai ^^ thx god, thx everyone .. now i just need to inject the value


问:
Query for extract string from xml in sql
In SQL Server 2012, I have a table  DEFINITIONS and a column in it that value of it is XML and name of column is "XML". I want to extract string "[CDATA[xxxx]]" from XML column (in parameter tag). how can I do that?

XML Example value:

```<code><CatalogItem subType="0" type="82">
   <id>7c75be9f-d490-4ff5-81ed-064349f4efde</id>
   <name>Test White</name>
   <description />
   <attributes>0</attributes>
   <parameters><conditions><condition grouping="or"><prop-key>usb_device_serial_number</prop-key><op-key>equals</op-key><value><![CDATA[gdefgd||]]></value></condition></conditions></parameters>
   <customParameterNames />
   <enforceProducts>
     <Product type="WIN" />
   </enforceProducts>
   </CatalogItem>
</code>```

Update 1

This Query solve my problem:

```<code>if object_id('dbo.cdata') is not null drop table dbo.cdata;
create table dbo.cdata(
  x xml
);
insert into dbo.cdata(x)
  SELECT XML FROM [HQ-MC-SRV-01].[dbo].[DEFINITIONS]
select
  xv.v.value('.', 'nvarchar(max)') as cdata
from dbo.cdata
cross apply
  cdata.x.nodes(
   '//parameters'
  ) as pp(p)
cross apply (
  values(
   cast(pp.p.value(
     '.', 'nvarchar(max)'
   ) as xml)
  )
 ) as xp(p)
cross apply
 xp.p.nodes('//value') as xv(v)
;
</code>```

Thanks a Lot, Andrei Odegov

Update 2

i have to extract "serialNumber" and "endUser" from this XML with previous query too.

```<code><CatalogItem subType="0" type="93">
 <id>9d6825e6-fa89-44e1-8e0f-61768016624c</id>
 <name>tteesstt</name>
 <description />
 <attributes>0</attributes>
 <entries>
  <entry>
    <serialNumber>zsxxdx</serialNumber>
    <userType>user</userType>
    <endUser>farhad@drf.local</endUser>
    <description />
  </entry>
 </entries>
</CatalogItem>
</code>```

Update 3

```<code> <CatalogItem subType="0" type="12">
  <id>169d6139-bdb6-4fff-88e6-09f00dd2f155</id>
  <name>za</name>
  <description />
  <attributes>0</attributes>
  <SIDMode>true</SIDMode>
  <nameIdentificationType>1</nameIdentificationType>
  <entries>
   <entry>
    <name>farhad</name>
    <path>CN=farhad,CN=Users,DC=DCVLAB,DC=LOCAL</path>
    <uid>F7A84834EAC8984AA7FBEAD7A5539432</uid>
    <serverName>192.168.7.2</serverName>
    <sid>S-1-5-21-907365782-933549064-1582919620-1103</sid>
    <type>user</type>
   <entry>
    <name>IT-MNG</name>
    <path>CN=IT,CN=Users,DC=sglab,DC=local</path>
    <uid>BEDC7DDF93A8D54DAC7A5CEE7307BF4F</uid>
    <serverName>192.168.7.201</serverName>
    <sid>S-1-5-21-3362085216-3357124804-2073486349-1107</sid>
    <type>user</type>
   </entry>
  </entries>
 </CatalogItem>
</code>```

答:
Taking into account your test data, you can try to adapt the following code:

```<code>declare @x xml = '
<CatalogItem subType="0" type="82">
   <id>7c75be9f-d490-4ff5-81ed-064349f4efde</id>
   <name>Test White</name>
   <description />
   <attributes>0</attributes>
   <parameters><conditions><condition grouping="or"><prop-key>usb_device_serial_number</prop-key><op-key>equals</op-key><value><![CDATA[gdefgd||]]></value></condition></conditions></parameters>
   <customParameterNames />
   <enforceProducts>
     <Product type="WIN" />
   </enforceProducts>
   </CatalogItem>
';

select cast(@x.value('(//parameters)[1]', 'nvarchar(max)') as xml).query('//value/text()') as cdata;
</code>```

Output

```<code>+----------+
|  cdata   |
+----------+
| gdefgd|| |
+----------+
</code>```

Update:

```<code>if object_id('dbo.cdata') is not null drop table dbo.cdata;

create table dbo.cdata(
  x xml
);

insert into dbo.cdata(x)
  values ('
<CatalogItem subType="0" type="82">
   <id>7c75be9f-d490-4ff5-81ed-064349f4efde</id>
   <name>Test White</name>
   <description />
   <attributes>0</attributes>
   <parameters><conditions><condition grouping="or"><prop-key>usb_device_serial_number</prop-key><op-key>equals</op-key><value><![CDATA[gdefgd||]]></value><value><![CDATA[foo]]></value></condition></conditions></parameters>
   <parameters><conditions><condition grouping="or"><prop-key>usb_device_serial_number</prop-key><op-key>equals</op-key><value><![CDATA[gdefgd||170]]></value><value><![CDATA[foo170]]></value></condition></conditions></parameters>
   <customParameterNames />
   <enforceProducts>
     <Product type="WIN" />
   </enforceProducts>
   </CatalogItem>
'), ('
<CatalogItem subType="0" type="82">
   <id>7c75be9f-d490-4ff5-81ed-064349f4efde</id>
   <name>Test White</name>
   <description />
   <attributes>0</attributes>
   <parameters><conditions><condition grouping="or"><prop-key>usb_device_serial_number</prop-key><op-key>equals</op-key><value><![CDATA[gdefgd||42]]></value><value><![CDATA[foo42]]></value></condition></conditions></parameters>
   <customParameterNames />
   <enforceProducts>
     <Product type="WIN" />
   </enforceProducts>
   </CatalogItem>
');

select
  xv.v.value('.', 'nvarchar(max)') as cdata
from dbo.cdata
cross apply
  cdata.x.nodes(
    '//parameters'
  ) as pp(p)
cross apply (
  values(
    cast(pp.p.value(
      '.', 'nvarchar(max)'
    ) as xml)
   )
  ) as xp(p)
cross apply
  xp.p.nodes('//value') as xv(v);
</code>```

Update #2:

You can get more detail information about working in Sql Server with XML data in the "XQuery Language Reference (SQL Server)".
There are two articles on the CROSS and OUTER APPLY operators with examples of their application to XML data.

```<code>select
  replace(xv.v.value('.', 'nvarchar(max)'), '|', '') as cdata,
  xci.ci.value('(//serialNumber)[1]', 'nvarchar(15)') as sn,
  xci.ci.value('(entries/entry/endUser)[1]', 'nvarchar(50)') as eu,
  xci.ci.value('(entries/entry/name)[1]', 'nvarchar(50)') as name
from dbo.cdata
cross apply
  cdata.x.nodes('/CatalogItem') as xci(ci)
outer apply
  xci.ci.nodes('parameters') as pp(p)
outer apply (
  values(
    cast(pp.p.value(
      '.', 'nvarchar(max)'
    ) as xml)
   )
  ) as xp(p)
outer apply
  xp.p.nodes('//value') as xv(v);
</code>```

Output:

```<code>+-----------+--------+------------------+--------+
|   cdata   |   sn   |        eu        |  name  |
+-----------+--------+------------------+--------+
| gdefgd    | zsxxdx | farhad@drf.local | NULL   |
| foo       | zsxxdx | farhad@drf.local | NULL   |
| gdefgd170 | zsxxdx | farhad@drf.local | NULL   |
| foo170    | zsxxdx | farhad@drf.local | NULL   |
| NULL      | foobar | user@mail.net    | NULL   |
| NULL      | NULL   | NULL             | farhad |
+-----------+--------+------------------+--------+
</code>```

Test it online with Rextester.

Body:
In SQL Server 2012, I have a table  DEFINITIONS and a column in it that value of it is XML and name of column is "XML". I want to extract string "[CDATA[xxxx]]" from XML column (in parameter tag). how can I do that?

XML Example value:

<CatalogItem subType="0" type="82">
   <id>7c75be9f-d490-4ff5-81ed-064349f4efde</id>
   <name>Test White</name>
   <description />
   <attributes>0</attributes>
   <parameters><conditions><condition grouping="or"><prop-key>usb_device_serial_number</prop-key><op-key>equals</op-key><value><![CDATA[gdefgd||]]></value></condition></conditions></parameters>
   <customParameterNames />
   <enforceProducts>
     <Product type="WIN" />
   </enforceProducts>
   </CatalogItem>

Update 1

This Query solve my problem:

if object_id('dbo.cdata') is not null drop table dbo.cdata;
create table dbo.cdata(
  x xml
);
insert into dbo.cdata(x)
  SELECT XML FROM [HQ-MC-SRV-01].[dbo].[DEFINITIONS]
select
  xv.v.value('.', 'nvarchar(max)') as cdata
from dbo.cdata
cross apply
  cdata.x.nodes(
   '//parameters'
  ) as pp(p)
cross apply (
  values(
   cast(pp.p.value(
     '.', 'nvarchar(max)'
   ) as xml)
  )
 ) as xp(p)
cross apply
 xp.p.nodes('//value') as xv(v)
;

Thanks a Lot, Andrei Odegov

Update 2

i have to extract "serialNumber" and "endUser" from this XML with previous query too.

<CatalogItem subType="0" type="93">
 <id>9d6825e6-fa89-44e1-8e0f-61768016624c</id>
 <name>tteesstt</name>
 <description />
 <attributes>0</attributes>
 <entries>
  <entry>
    <serialNumber>zsxxdx</serialNumber>
    <userType>user</userType>
    <endUser>farhad@drf.local</endUser>
    <description />
  </entry>
 </entries>
</CatalogItem>

Update 3

 <CatalogItem subType="0" type="12">
  <id>169d6139-bdb6-4fff-88e6-09f00dd2f155</id>
  <name>za</name>
  <description />
  <attributes>0</attributes>
  <SIDMode>true</SIDMode>
  <nameIdentificationType>1</nameIdentificationType>
  <entries>
   <entry>
    <name>farhad</name>
    <path>CN=farhad,CN=Users,DC=DCVLAB,DC=LOCAL</path>
    <uid>F7A84834EAC8984AA7FBEAD7A5539432</uid>
    <serverName>192.168.7.2</serverName>
    <sid>S-1-5-21-907365782-933549064-1582919620-1103</sid>
    <type>user</type>
   <entry>
    <name>IT-MNG</name>
    <path>CN=IT,CN=Users,DC=sglab,DC=local</path>
    <uid>BEDC7DDF93A8D54DAC7A5CEE7307BF4F</uid>
    <serverName>192.168.7.201</serverName>
    <sid>S-1-5-21-3362085216-3357124804-2073486349-1107</sid>
    <type>user</type>
   </entry>
  </entries>
 </CatalogItem>

Body:
Taking into account your test data, you can try to adapt the following code:

declare @x xml = '
<CatalogItem subType="0" type="82">
   <id>7c75be9f-d490-4ff5-81ed-064349f4efde</id>
   <name>Test White</name>
   <description />
   <attributes>0</attributes>
   <parameters>&lt;conditions&gt;&lt;condition grouping="or"&gt;&lt;prop-key&gt;usb_device_serial_number&lt;/prop-key&gt;&lt;op-key&gt;equals&lt;/op-key&gt;&lt;value&gt;&lt;![CDATA[gdefgd||]]&gt;&lt;/value&gt;&lt;/condition&gt;&lt;/conditions&gt;</parameters>
   <customParameterNames />
   <enforceProducts>
     <Product type="WIN" />
   </enforceProducts>
   </CatalogItem>
';

select cast(@x.value('(//parameters)[1]', 'nvarchar(max)') as xml).query('//value/text()') as cdata;

Output

+----------+
|  cdata   |
+----------+
| gdefgd|| |
+----------+

Update:

if object_id('dbo.cdata') is not null drop table dbo.cdata;

create table dbo.cdata(
  x xml
);

insert into dbo.cdata(x)
  values ('
<CatalogItem subType="0" type="82">
   <id>7c75be9f-d490-4ff5-81ed-064349f4efde</id>
   <name>Test White</name>
   <description />
   <attributes>0</attributes>
   <parameters>&lt;conditions&gt;&lt;condition grouping="or"&gt;&lt;prop-key&gt;usb_device_serial_number&lt;/prop-key&gt;&lt;op-key&gt;equals&lt;/op-key&gt;&lt;value&gt;&lt;![CDATA[gdefgd||]]&gt;&lt;/value&gt;&lt;value&gt;&lt;![CDATA[foo]]&gt;&lt;/value&gt;&lt;/condition&gt;&lt;/conditions&gt;</parameters>
   <parameters>&lt;conditions&gt;&lt;condition grouping="or"&gt;&lt;prop-key&gt;usb_device_serial_number&lt;/prop-key&gt;&lt;op-key&gt;equals&lt;/op-key&gt;&lt;value&gt;&lt;![CDATA[gdefgd||170]]&gt;&lt;/value&gt;&lt;value&gt;&lt;![CDATA[foo170]]&gt;&lt;/value&gt;&lt;/condition&gt;&lt;/conditions&gt;</parameters>
   <customParameterNames />
   <enforceProducts>
     <Product type="WIN" />
   </enforceProducts>
   </CatalogItem>
'), ('
<CatalogItem subType="0" type="82">
   <id>7c75be9f-d490-4ff5-81ed-064349f4efde</id>
   <name>Test White</name>
   <description />
   <attributes>0</attributes>
   <parameters>&lt;conditions&gt;&lt;condition grouping="or"&gt;&lt;prop-key&gt;usb_device_serial_number&lt;/prop-key&gt;&lt;op-key&gt;equals&lt;/op-key&gt;&lt;value&gt;&lt;![CDATA[gdefgd||42]]&gt;&lt;/value&gt;&lt;value&gt;&lt;![CDATA[foo42]]&gt;&lt;/value&gt;&lt;/condition&gt;&lt;/conditions&gt;</parameters>
   <customParameterNames />
   <enforceProducts>
     <Product type="WIN" />
   </enforceProducts>
   </CatalogItem>
');

select
  xv.v.value('.', 'nvarchar(max)') as cdata
from dbo.cdata
cross apply
  cdata.x.nodes(
    '//parameters'
  ) as pp(p)
cross apply (
  values(
    cast(pp.p.value(
      '.', 'nvarchar(max)'
    ) as xml)
   )
  ) as xp(p)
cross apply
  xp.p.nodes('//value') as xv(v);

Update #2:

You can get more detail information about working in Sql Server with XML data in the "XQuery Language Reference (SQL Server)".
There are two articles on the CROSS and OUTER APPLY operators with examples of their application to XML data.

select
  replace(xv.v.value('.', 'nvarchar(max)'), '|', '') as cdata,
  xci.ci.value('(//serialNumber)[1]', 'nvarchar(15)') as sn,
  xci.ci.value('(entries/entry/endUser)[1]', 'nvarchar(50)') as eu,
  xci.ci.value('(entries/entry/name)[1]', 'nvarchar(50)') as name
from dbo.cdata
cross apply
  cdata.x.nodes('/CatalogItem') as xci(ci)
outer apply
  xci.ci.nodes('parameters') as pp(p)
outer apply (
  values(
    cast(pp.p.value(
      '.', 'nvarchar(max)'
    ) as xml)
   )
  ) as xp(p)
outer apply
  xp.p.nodes('//value') as xv(v);

Output:

+-----------+--------+------------------+--------+
|   cdata   |   sn   |        eu        |  name  |
+-----------+--------+------------------+--------+
| gdefgd    | zsxxdx | farhad@drf.local | NULL   |
| foo       | zsxxdx | farhad@drf.local | NULL   |
| gdefgd170 | zsxxdx | farhad@drf.local | NULL   |
| foo170    | zsxxdx | farhad@drf.local | NULL   |
| NULL      | foobar | user@mail.net    | NULL   |
| NULL      | NULL   | NULL             | farhad |
+-----------+--------+------------------+--------+

Test it online with Rextester.


问:
Matlab and Arduino serial data
I am sending a string data to Arduino from Matlab using the following code:

```<code>clear s;
s=serial('COM4','BAUD', 9600);  % Baud rate and COM port
fopen(s);
value1=('11,222;333<444>555?666');
display('data sent');
fprintf(s,'%s\n',value1);
fclose(s);
</code>```

I am receiving and processing the string in Arduino using the following code:

```<code>String command;
int i;
float data_rec;
void setup() {
  // put your setup code here, to run once:
  command="11,222;333<444>555?666";
  Serial.begin(9600);
}
void loop() {
  if(Serial.available() >0){
    String command=Serial.readString();
    parseCommand(command);
    data_rec=Serial.parseInt();
    Serial.println("data_rec");
    Serial.println(data_rec);
  }
}

void parseCommand(String com){
  String F_d;
  String E_m;
  String L_p;
  String S_v;
  String H_d;
  String L_t;

  F_d=com.substring(0,com.indexOf(','));
  E_m=com.substring(com.indexOf(',')+1,com.indexOf(';'));
  L_p=com.substring(com.indexOf(';')+1,com.indexOf('<'));
  S_v=com.substring(com.indexOf('<')+1,com.indexOf('>'));
  H_d=com.substring(com.indexOf('>')+1,com.indexOf('?'));
  L_t=com.substring(com.indexOf('?')+1,com.length());

 Serial.println(com);
 Serial.println("F_d:");
 Serial.println(F_d);
 Serial.println("E_m:");
 Serial.println(E_m);
 Serial.println("L_p:");
 Serial.println(L_p);
 Serial.println("S_v:");
 Serial.println(S_v);
 Serial.println("H_d:");
 Serial.println(H_d);
 Serial.println("L_t:");
 Serial.println(L_t);
}
</code>```

This does not work with Matlab.  However, when I send the same string from the Serial Monitor, it seems to work.

Why aren't I getting any output for the Matlab code?  I am checking the data sent and received by Arduino over serial by monitoring the serial port using Serial Monitoring Studio.

答:
You have to set a break. Because the Arduino restarts after fopen ...</p>

```<code>clear s;
s=serial('COM4','BAUD', 9600);  % Baud rate and COM port
fopen(s);
pause(1);
value1=('11,222;333<444>555?666');
display('data sent');
fprintf(s,'%s\n',value1);
fclose(s);
</code>```

Title: Matlab and Arduino serial data

Body:
I am sending a string data to Arduino from Matlab using the following code:

clear s;
s=serial('COM4','BAUD', 9600);  % Baud rate and COM port
fopen(s);
value1=('11,222;333<444>555?666');
display('data sent');
fprintf(s,'%s\n',value1);
fclose(s);

I am receiving and processing the string in Arduino using the following code:

String command;
int i;
float data_rec;
void setup() {
  // put your setup code here, to run once:
  command="11,222;333<444>555?666";
  Serial.begin(9600);
}
void loop() {
  if(Serial.available() >0){
    String command=Serial.readString();
    parseCommand(command);
    data_rec=Serial.parseInt();
    Serial.println("data_rec");
    Serial.println(data_rec);
  }
}

void parseCommand(String com){
  String F_d;
  String E_m;
  String L_p;
  String S_v;
  String H_d;
  String L_t;

  F_d=com.substring(0,com.indexOf(','));
  E_m=com.substring(com.indexOf(',')+1,com.indexOf(';'));
  L_p=com.substring(com.indexOf(';')+1,com.indexOf('<'));
  S_v=com.substring(com.indexOf('<')+1,com.indexOf('>'));
  H_d=com.substring(com.indexOf('>')+1,com.indexOf('?'));
  L_t=com.substring(com.indexOf('?')+1,com.length());

 Serial.println(com);
 Serial.println("F_d:");
 Serial.println(F_d);
 Serial.println("E_m:");
 Serial.println(E_m);
 Serial.println("L_p:");
 Serial.println(L_p);
 Serial.println("S_v:");
 Serial.println(S_v);
 Serial.println("H_d:");
 Serial.println(H_d);
 Serial.println("L_t:");
 Serial.println(L_t);
}

This does not work with Matlab.  However, when I send the same string from the Serial Monitor, it seems to work.

Why aren't I getting any output for the Matlab code?  I am checking the data sent and received by Arduino over serial by monitoring the serial port using Serial Monitoring Studio.

Body:
You have to set a break. Because the Arduino restarts after fopen ...

clear s;
s=serial('COM4','BAUD', 9600);  % Baud rate and COM port
fopen(s);
pause(1);
value1=('11,222;333<444>555?666');
display('data sent');
fprintf(s,'%s\n',value1);
fclose(s);


答: If you are going with segue to other view controller you can pass data there, first add an identifier to the segue then in prepare(for segue:... you will have access to segue.destination as? View_2, then do the same with container and pass the value

Title: How to pass data from a TableViewCell to a ContainerView?

Body:
I'm new in using Swift and need help to pass data from a TableViewCell to a ContainerView to change some text of Labels.

My current status is to passing data from a TabelViewCell to a ViewController to change the text of a Label (IBOutlet) into a second ViewController with a segue.

But I don't know how to pass data from a Cell to a ContainerView with my own ViewController.

Here is a picture of my project

Here you can find the picture of my project and problem

I just want to pass data from a TableViewCell of my "View_1" to "View_2" and change the text of the Label "Change_Text_1" in the ViewController "View_In_Container" of my ContainerView (UIView).

Perhaps you guys can help me with my problem. Thank you.