问:
Push notifications are not delivered anymore after relaunching app from Xcode Swift
I'm finally able to send push notifications via Firebase between my two apps. The problem is that on App1 only works when fresh installed on device. If I stop and run again the project push notifications are not delivered anymore even if fcmTokenhasn't changed, and in App2 I get error :

```<code>POST:
    {"multicast_id":6763498783850594663,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"NotRegistered"}]}
</code>```

meaning Firebase didn't find a valid fcmTokento send the push to. While on App1 first install console print :

didReceiveRegistrationToken: Firebase registration token:
  eI8nx-zroBU:APA91bG9gZeukgfsxobw4C3mg0Jhro06ALUQqtJwjfYxIwv4hIvjFwNWpSc_0JHPtl2FAGb-Jqwk7GL5pgki_Q_awOngA8yP66IG9fpWKQjEuS330N_c3yMAQvDUBCVo7wbFET_oEqLu

is correct to have as I set it up in  didReceiveRegistrationToken delegate method, on second launch didReceiveRegistrationToken gives the same token as before. As I understood if a new fcmToken is delivered is didRefreshRegistrationTokenthat gets called, but I have no prints from that delegate method, so seems that earlier fcmToken is still valid.
Can you see where I set it up wrong?

didFinishLaunchingWithOptions:

```<code>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        window?.tintColor = UIColor.blue
        // Use Firebase library to configure APIs
        FirebaseApp.configure()
        Messaging.messaging().delegate = self
        Crashlytics().debugMode = true
        Fabric.with([Crashlytics.self])
        // setting up notification delegate
        if #available(iOS 10.0, *) {
            //iOS 10.0 and greater
            UNUserNotificationCenter.current().delegate = self
            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
            //Solicit permission from the user to receive notifications
            UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: { granted, error in
                DispatchQueue.main.async {
                    if granted {
                        print("didFinishLaunchingWithOptions iOS 10: Successfully registered for APNs")
                        UIApplication.shared.registerForRemoteNotifications() // declaring it work perfetcly
                        UIApplication.shared.applicationIconBadgeNumber = 0
                    } else {
                        //Do stuff if unsuccessful...
                        print("didFinishLaunchingWithOptions iOO 10: Error in registering for APNs: \(String(describing: error))")
                    }
                }
            })
        } else {
            //iOS 9
            let type: UIUserNotificationType = [UIUserNotificationType.badge, UIUserNotificationType.alert, UIUserNotificationType.sound]
            let setting = UIUserNotificationSettings(types: type, categories: nil)
            UIApplication.shared.registerUserNotificationSettings(setting)
            UIApplication.shared.registerForRemoteNotifications() // declaring it work perfetcly
            UIApplication.shared.applicationIconBadgeNumber = 0
            print("didFinishLaunchingWithOptions iOS 9: Successfully registered for APNs")
        }
        //get application instance ID
//        InstanceID.instanceID().instanceID { (result, error) in
//            if let error = error {
//                print("didFinishLaunchingWithOptions: Error fetching remote instance ID: \(error)")
//            } else if let result = result {
//                print("didFinishLaunchingWithOptions: Remote instance ID token: \(result.token)")
//            }
//        }
        // setting up remote control values
        let _ = RCValues.sharedInstance
        GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID
        Crashlytics().debugMode = true
        Fabric.with([Crashlytics.self])
        //        // TODO: Move this to where you establish a user session
        //        self.logUser()
        var error: NSError?
        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        } catch let error1 as NSError{
            error = error1
            print("could not set session. err:\(error!.localizedDescription)")
        }
        do {
            try AVAudioSession.sharedInstance().setActive(true)
        } catch let error1 as NSError{
            error = error1
            print("could not active session. err:\(error!.localizedDescription)")
        }
        // goggle only
        GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID
//        GIDSignIn.sharedInstance().delegate = self
        // Facebook SDK
        return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
//        return true
    }
</code>```

didRegisterForRemoteNotificationsWithDeviceToken:

```<code>func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let tokenParts = deviceToken.map { data -> String in
            return String(format: "%02.2hhx", data)
        }
        let token = tokenParts.joined()
        print(" didRegisterForRemoteNotificationsWithDeviceToken : devcice token is: \(token)")
        Messaging.messaging().apnsToken = deviceToken
    }
</code>```

didReceiveRegistrationToken:

```<code>func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        print("didReceiveRegistrationToken: Firebase registration token: \(fcmToken)")
        let dataDict:[String: String] = ["token": fcmToken]
        NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
        // TODO: If necessary send token to application server.
        AppDelegate.fcmToken = fcmToken

        if userDetails.fullName != nil {
            userDetails.fcmToken = fcmToken
            Firebase.updateToken(completed: { (true) in
                print("AppDelegate.didFinishLaunchingWithOptions: token updloaded to Firebase, will now save it to CoreData")
            }, token: fcmToken)
        }
        // Note: This callback is fired at each app startup and whenever a new token is generated.
    }
</code>```

didRefreshRegistrationToken:

```<code>func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
        let dataDict:[String: String] = ["token": fcmToken]
        NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
//        print("Refreshed Token: \(fcmToken)")
        AppDelegate.fcmToken = fcmToken
        if userDetails.fullName != nil {
            userDetails.fcmToken = fcmToken
            Firebase.updateToken(completed: { (true) in
                print("AppDelegate.didRefreshRegistrationToken: token updloaded to Firebase, will now save it to CoreData")
            }, token: fcmToken)
        }
    }
</code>```

答:
Problem seem to be solved. After updating the pods, it now works as expected. I had to delete App1 from device and reinstalling it as fast my first attempt to just run the project again the problem was still there. After cleaning the build, deleting the app from device and reinstalling it it now keeps receiving push notifications after I relaunch the project.
Hope this will help others, as I struggled a lot to implement device to device push notifications, and haven't found many helpful info about it.</p>

Body:
I'm finally able to send push notifications via Firebase between my two apps. The problem is that on App1 only works when fresh installed on device. If I stop and run again the project push notifications are not delivered anymore even if fcmTokenhasn't changed, and in App2 I get error :

POST:
    {"multicast_id":6763498783850594663,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"NotRegistered"}]}

meaning Firebase didn't find a valid fcmTokento send the push to. While on App1 first install console print :

didReceiveRegistrationToken: Firebase registration token:
  eI8nx-zroBU:APA91bG9gZeukgfsxobw4C3mg0Jhro06ALUQqtJwjfYxIwv4hIvjFwNWpSc_0JHPtl2FAGb-Jqwk7GL5pgki_Q_awOngA8yP66IG9fpWKQjEuS330N_c3yMAQvDUBCVo7wbFET_oEqLu

is correct to have as I set it up in  didReceiveRegistrationToken delegate method, on second launch didReceiveRegistrationToken gives the same token as before. As I understood if a new fcmToken is delivered is didRefreshRegistrationTokenthat gets called, but I have no prints from that delegate method, so seems that earlier fcmToken is still valid.
Can you see where I set it up wrong?

didFinishLaunchingWithOptions:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        window?.tintColor = UIColor.blue
        // Use Firebase library to configure APIs
        FirebaseApp.configure()
        Messaging.messaging().delegate = self
        Crashlytics().debugMode = true
        Fabric.with([Crashlytics.self])
        // setting up notification delegate
        if #available(iOS 10.0, *) {
            //iOS 10.0 and greater
            UNUserNotificationCenter.current().delegate = self
            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
            //Solicit permission from the user to receive notifications
            UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: { granted, error in
                DispatchQueue.main.async {
                    if granted {
                        print("didFinishLaunchingWithOptions iOS 10: Successfully registered for APNs")
                        UIApplication.shared.registerForRemoteNotifications() // declaring it work perfetcly
                        UIApplication.shared.applicationIconBadgeNumber = 0
                    } else {
                        //Do stuff if unsuccessful...
                        print("didFinishLaunchingWithOptions iOO 10: Error in registering for APNs: \(String(describing: error))")
                    }
                }
            })
        } else {
            //iOS 9
            let type: UIUserNotificationType = [UIUserNotificationType.badge, UIUserNotificationType.alert, UIUserNotificationType.sound]
            let setting = UIUserNotificationSettings(types: type, categories: nil)
            UIApplication.shared.registerUserNotificationSettings(setting)
            UIApplication.shared.registerForRemoteNotifications() // declaring it work perfetcly
            UIApplication.shared.applicationIconBadgeNumber = 0
            print("didFinishLaunchingWithOptions iOS 9: Successfully registered for APNs")
        }
        //get application instance ID
//        InstanceID.instanceID().instanceID { (result, error) in
//            if let error = error {
//                print("didFinishLaunchingWithOptions: Error fetching remote instance ID: \(error)")
//            } else if let result = result {
//                print("didFinishLaunchingWithOptions: Remote instance ID token: \(result.token)")
//            }
//        }
        // setting up remote control values
        let _ = RCValues.sharedInstance
        GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID
        Crashlytics().debugMode = true
        Fabric.with([Crashlytics.self])
        //        // TODO: Move this to where you establish a user session
        //        self.logUser()
        var error: NSError?
        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        } catch let error1 as NSError{
            error = error1
            print("could not set session. err:\(error!.localizedDescription)")
        }
        do {
            try AVAudioSession.sharedInstance().setActive(true)
        } catch let error1 as NSError{
            error = error1
            print("could not active session. err:\(error!.localizedDescription)")
        }
        // goggle only
        GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID
//        GIDSignIn.sharedInstance().delegate = self
        // Facebook SDK
        return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
//        return true
    }

didRegisterForRemoteNotificationsWithDeviceToken:

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let tokenParts = deviceToken.map { data -> String in
            return String(format: "%02.2hhx", data)
        }
        let token = tokenParts.joined()
        print(" didRegisterForRemoteNotificationsWithDeviceToken : devcice token is: \(token)")
        Messaging.messaging().apnsToken = deviceToken
    }

didReceiveRegistrationToken:

func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        print("didReceiveRegistrationToken: Firebase registration token: \(fcmToken)")
        let dataDict:[String: String] = ["token": fcmToken]
        NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
        // TODO: If necessary send token to application server.
        AppDelegate.fcmToken = fcmToken

        if userDetails.fullName != nil {
            userDetails.fcmToken = fcmToken
            Firebase.updateToken(completed: { (true) in
                print("AppDelegate.didFinishLaunchingWithOptions: token updloaded to Firebase, will now save it to CoreData")
            }, token: fcmToken)
        }
        // Note: This callback is fired at each app startup and whenever a new token is generated.
    }

didRefreshRegistrationToken:

func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
        let dataDict:[String: String] = ["token": fcmToken]
        NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
//        print("Refreshed Token: \(fcmToken)")
        AppDelegate.fcmToken = fcmToken
        if userDetails.fullName != nil {
            userDetails.fcmToken = fcmToken
            Firebase.updateToken(completed: { (true) in
                print("AppDelegate.didRefreshRegistrationToken: token updloaded to Firebase, will now save it to CoreData")
            }, token: fcmToken)
        }
    }


来源: stackexchange

问:
how to use a different name for my class property than the sql column name
For example, if I wanted my class property to be named like this for a laugh:

```<code>class Product
{
   [Key]
   int ProductID {get;set;}

   [Required]
   string TitleTOTHEMAX {get;set;}
}
</code>```

My Sql table has 2 columns "ProductID" and "Title", how do I tell the class's property to map itself to "Title" column considering the "TitleTOTHEMAX" column does not exist :)

答:
You should use Fluent Api with those kind of configuration.</p>

```<code>protected override void OnModelCreating(ModelBuilder modelBuilder)
{
     modelBuilder.Entity<Product>()
    .Property(x => x.TitleTOTHEMAX )
    .HasColumnName("Title")
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
For example, if I wanted my class property to be named like this for a laugh:

class Product
{
   [Key]
   int ProductID {get;set;}

   [Required]
   string TitleTOTHEMAX {get;set;}
}

My Sql table has 2 columns "ProductID" and "Title", how do I tell the class's property to map itself to "Title" column considering the "TitleTOTHEMAX" column does not exist :)

Body:
You should use Fluent Api with those kind of configuration.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
     modelBuilder.Entity<Product>()
    .Property(x => x.TitleTOTHEMAX )
    .HasColumnName("Title")
}

ContentLicense: CC BY-SA 4.0


问:
Adding Semicolon in array of booksName after each BookName , How to change the last semicolon to (And)
I need and example for adding (semicolon) after each bookName in array of bookName , and change the last semicolon to (and) ,
What i have is {"me befor you","fallen","inferno"}
what i need as a result is (me befor you , fallen and inferno)</p>

答:
Right, so this is really quite a simple thing to do (As I said in the comments):

```<code>books := []string{"title 1", "title 2", "title 3"}
list := fmt.Sprintf(
    "%s and %s",
    strings.Join(books[:len(books)-1], ", "), // join all elements with , excluding last one|
    books[len(books)-1], // last element in slice
)
</code>```

Demo

How it works:

strings.Join is part of the standard package strings, which does what your home-grown impode function does. No need to write it yourself

books[:len(books)-1] "creates" a new slice containing all elements in the original slice, excluding the last one. Joining these elements with comma's is what you want. You just want an and bit between this and the last element in the slice.

books[len(books)-1] gets the last element in the slice

fmt.Sprintf("%s and %s": this creates a string where the first part is the comma separated list created by strings.Join, and the second part is the last element in the slice.

Together this yields "title 1, title 2 and title 3"

Body:
Right, so this is really quite a simple thing to do (As I said in the comments):

books := []string{"title 1", "title 2", "title 3"}
list := fmt.Sprintf(
    "%s and %s",
    strings.Join(books[:len(books)-1], ", "), // join all elements with , excluding last one|
    books[len(books)-1], // last element in slice
)

Demo

How it works:

strings.Join is part of the standard package strings, which does what your home-grown impode function does. No need to write it yourself

books[:len(books)-1] "creates" a new slice containing all elements in the original slice, excluding the last one. Joining these elements with comma's is what you want. You just want an and bit between this and the last element in the slice.

books[len(books)-1] gets the last element in the slice

fmt.Sprintf("%s and %s": this creates a string where the first part is the comma separated list created by strings.Join, and the second part is the last element in the slice.

Together this yields "title 1, title 2 and title 3"


问:
My PyQt application not works with error - This application failed to start because no Qt platform
I developed a Python program using PyQt5 in Windows 10, and it works very well. Then i made it into .exe file with pyinstaller, but it failed and gave me an error.

```<code>This application failed to start because no Qt platform plugin could be initialized.
Reinstalling the application may fix this problem.

Available platform plugins are: minimal, offscreen, webgl, windows.
</code>```

I searched for similar problems in here and google, but i couldn't find the same problem - running .py works well but .exe failed.

Followings are what i have tried:

Placing platforms folder in the same directory with .exe file.

Setting environment variable QT_QPA_PLATFORM_PLUGIN_PATH. (it was already set.)

Body:
I developed a Python program using PyQt5 in Windows 10, and it works very well. Then i made it into .exe file with pyinstaller, but it failed and gave me an error.

This application failed to start because no Qt platform plugin could be initialized.
Reinstalling the application may fix this problem.

Available platform plugins are: minimal, offscreen, webgl, windows.

I searched for similar problems in here and google, but i couldn't find the same problem - running .py works well but .exe failed.

Followings are what i have tried:

Placing platforms folder in the same directory with .exe file.

Setting environment variable QT_QPA_PLATFORM_PLUGIN_PATH. (it was already set.)

Body:
First, try the latest version of Pyinstaller because it has some new fixes for PyQt5.
Second try to install latest version of pyqt5 with pip install -U pyqt5.
Last but not least, don't use UPX with PyQt5 because it can't properly compress all DLLs.

So you can simply freeze your application without any problem just run:
pyinstaller -F --noupx <script_name>.py.

If you still have problem replace the files in bin and plugins directories in
C:\Users\USERNAME\AppData\Roaming\pyinstaller\bincache00_py37_64bit\pyqt5\qt

from

C:\Program Files\Python37\Lib\site-packages\PyQt5\Qt

and run pyinstaller <script_name>.spec


问:
Calling functions and returning values
I am a beginner in C++.I have a function which returns some parameters that i need ,to use in  the rest of my program.I am trying to access that function within another class.I am confused with the way i can do it...Can anyone please help me..?

Following is my code :

```<code> void SampleProgram :: myFunction()
   {
         string sInput;
         GetInfo  getInfo(sInput);  //creating instance of the class containing the function

            string sSw="";
       string sName="ram";
       string sList="list";

           getInfo.getRequiredInfo(sSw,sName,sList); //calling the function

    }
</code>```

How can i access the output parameters of getRequiredInfo() ..?and save it if the ouput parameters are as following :string name,int status
Please help me...

答:
You can able to return single value in function.

so You can create struct containing string and int and return that as the result.

```<code>    struct
    {
           string name;
            int    k;
    }result;
    result r = getInfo.getRequiredInfo(sSw,sName,sList); //calling the function
</code>```

you can save the output parameters like these:

```<code>   string _name;
   int       nk;

   _name = r.name;
   nk    = r.k;
</code>```

Title: Calling functions and returning values

Body:
I am a beginner in C++.I have a function which returns some parameters that i need ,to use in  the rest of my program.I am trying to access that function within another class.I am confused with the way i can do it...Can anyone please help me..?

Following is my code :

 void SampleProgram :: myFunction()
   {
         string sInput;
         GetInfo  getInfo(sInput);  //creating instance of the class containing the function

            string sSw="";
       string sName="ram";
       string sList="list";

           getInfo.getRequiredInfo(sSw,sName,sList); //calling the function

    }

How can i access the output parameters of getRequiredInfo() ..?and save it if the ouput parameters are as following :string name,int status
Please help me...

Body:
You can able to return single value in function.

so You can create struct containing string and int and return that as the result.

    struct
    {
           string name;
            int    k;
    }result;
    result r = getInfo.getRequiredInfo(sSw,sName,sList); //calling the function

you can save the output parameters like these:

   string _name;
   int       nk;

   _name = r.name;
   nk    = r.k;


问:
exception {'Id'} is already being tracked on ChangePasswordAsync()
I'm trying to update the password in  identity and I've run into the following error:

The instance of entity type 'TblUsers' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.

```<code>var changePasswordResult = await _userManager.ChangePasswordAsync(user: userData, currentPassword: Old, newPassword: New);
</code>```

what am I do to solve this exception?

答:
Based on the exception, userData is an instance of your Identity user class that you newed up, but you have previously queried that same user (which has the effect of adding to EF's object cache and change tracking). You're now trying to change the password using the instance that you newed up (which isn't tracked) instead of the instance pulled from the database (which is).

Long and short, if you're going to modify an entity, you should always use an instance pulled from the database to do so, not one you've newed up yourself. If the instance that was pulled from the database is around in this code, then use that. If it isn't, then pull it out of the context again (it will come from the object cache, so no additional query is necessary). Then, use that instance to change the password on.

Body:
I'm trying to update the password in  identity and I've run into the following error:

The instance of entity type 'TblUsers' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.

var changePasswordResult = await _userManager.ChangePasswordAsync(user: userData, currentPassword: Old, newPassword: New);

what am I do to solve this exception?


问:
Use apply on a data class in Kotlin
I know how to use the apply function on a normal Kotlin class but have not been able to use it with a data class:

```<code>data class Person(name: String)

val person = Person().apply {
    name = "Tony Stark"
}
</code>```

I get a compile message of:

No value passed for parameter 'name'

答:
The apply function works similar with any class. But there are some errors in your code snippet:

Parameter in Person constructor didn't mentioned as var or val, so there is no fields name in that class. It would be better to make it var to be able to change value.

You made class's constructor with 1 parameter, but trying to use empty constructor - it is error.

Title: Use apply on a data class in Kotlin

Body:
I know how to use the apply function on a normal Kotlin class but have not been able to use it with a data class:

data class Person(name: String)

val person = Person().apply {
    name = "Tony Stark"
}

I get a compile message of:

No value passed for parameter 'name'


问:
How do I create a collapsible like Bootstrap in AMP?
I am trying to create a collapsible in AMP with a sleek animation like Bootstrap has.

Now, I can create a collapsible with toggling a class and adjusting some height with CSS, but if I do so I will be giving a fixed height for all the collapsible, and since the content height won't be same for all the block, I cannot give the height.

In JavaScript, I could calculate the height of the content, and animate the height accordingly, but since we cannot use JavaScript in AMP, is there any way to do this?

I have tried doing it with css. I defined two classes one that hides the content by setting height to 0, and another shows the content by setting height to auto. It works, but it didn't have any animation. However, If I set height to some pixels instead of auto, and add some css transition, it works. But I don't want to give some static height for all the block.

```<code><!- Hidden -->
<div class="rich-text-block">
   <h3>Pathological Criteria</h3>
   <div class="richtext-content">If either is positive, diagnosis is definite (see Reference for exceptions)</div>
</div>
</code>```

```<code><!- Shown -->
<div class="rich-text-block shown">
   <h3>Pathological Criteria</h3>
   <div class="richtext-content">If either is positive, diagnosis is definite (see Reference for exceptions)</div>
</div>
</code>```

```<code>.rich-text-block .richtext-content {
    overflow: hidden;
    transition: height 0.3s linear;
    height: 0;
}
rich-text-block.shown .richtext-content {
    height: auto;
}
</code>```

I hope I am clear enough.

Thanks in advance

答:
You can try amp-accordion for your use case.

Coming to your issue.
You can not transition height with value auto. You can use max-height in the transition and set a max-height to something bigger than your box height will ever get.

The problem with this approach is transition will be based on max-height so if the height of all your boxes is almost the same, all the transitions will look almost identical, but if the heights of all your boxes are very much different then the transition duration of all your boxes won't look identical.

```<code>.rich-text-block .richtext-content {
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.3s linear;
}
rich-text-block.shown .richtext-content {
    max-height: 50px;
}
</code>```

Body:
I am trying to create a collapsible in AMP with a sleek animation like Bootstrap has.

Now, I can create a collapsible with toggling a class and adjusting some height with CSS, but if I do so I will be giving a fixed height for all the collapsible, and since the content height won't be same for all the block, I cannot give the height.

In JavaScript, I could calculate the height of the content, and animate the height accordingly, but since we cannot use JavaScript in AMP, is there any way to do this?

I have tried doing it with css. I defined two classes one that hides the content by setting height to 0, and another shows the content by setting height to auto. It works, but it didn't have any animation. However, If I set height to some pixels instead of auto, and add some css transition, it works. But I don't want to give some static height for all the block.

<!- Hidden -->

Pathological Criteria

If either is positive, diagnosis is definite (see Reference for exceptions)

<!- Shown -->

Pathological Criteria

If either is positive, diagnosis is definite (see Reference for exceptions)

.rich-text-block .richtext-content {
    overflow: hidden;
    transition: height 0.3s linear;
    height: 0;
}
rich-text-block.shown .richtext-content {
    height: auto;
}

I hope I am clear enough.

Thanks in advance

Body:
You can try amp-accordion for your use case.

Coming to your issue.
You can not transition height with value auto. You can use max-height in the transition and set a max-height to something bigger than your box height will ever get.

The problem with this approach is transition will be based on max-height so if the height of all your boxes is almost the same, all the transitions will look almost identical, but if the heights of all your boxes are very much different then the transition duration of all your boxes won't look identical.

.rich-text-block .richtext-content {
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.3s linear;
}
rich-text-block.shown .richtext-content {
    max-height: 50px;
}


问:
Getting column names from dataset
I'm trying to get the column names from a dirty dataset. The name of the column names start before the symbol "=". Is there a quick method to do this without looping over all the data?
How it looks now</p>

```<code>import pandas as pd
import numpy as np

missing_values=["n/a", "na", "--"]

df = pd.read_csv("data/data_bestand_3.txt", sep="&", na_values=missing_values)
df.head()
</code>```

答:
Looks like you're reading your first row as the header names. In the read_csv method, pass the argument header=None. Use Series.str.split to set your column names:

```<code>missing_values=["n/a", "na", "--"]
df = pd.read_csv("data/data_bestand_3.txt", sep="&", na_values=missing_values, header=None)

df.columns = df.loc[0].str.split('=').str[0].values
</code>```

Title: Getting column names from dataset

Body:
I'm trying to get the column names from a dirty dataset. The name of the column names start before the symbol "=". Is there a quick method to do this without looping over all the data?
How it looks now

import pandas as pd
import numpy as np

missing_values=["n/a", "na", "--"]

df = pd.read_csv("data/data_bestand_3.txt", sep="&", na_values=missing_values)
df.head()

Body:
Looks like you're reading your first row as the header names. In the read_csv method, pass the argument header=None. Use Series.str.split to set your column names:

missing_values=["n/a", "na", "--"]
df = pd.read_csv("data/data_bestand_3.txt", sep="&", na_values=missing_values, header=None)

df.columns = df.loc[0].str.split('=').str[0].values


问:
update in nested_forms
Im using Rails 3.0.3

I have a Model Bill:

```<code>class Bill < ActiveRecord::Base
   has_many :entries
   accepts_nested_attributes_for :entries

end
</code>```

In my Bill view i am using nested forms to create new entries in bills and with Javascript i insert existing entries with at this point, have no bill_id:

```<code>$("#row" + nested_form_id).append("<input type='hidden' name='bill[entries_attributes][" + nested_form_id + "][id]' id='bill_entries_attributes_" + nested_form_id + "_id' value='" + id +"' >");
</code>```

when i submit the form i get this error:

```<code>ActiveRecord::RecordNotFound (Couldn't find Entry with ID=127 for Bill with ID=):
  app/controllers/bills_controller.rb:121:in `new'
  app/controllers/bills_controller.rb:121:in `create'
</code>```

so the problem is, that rails is looking for the entry in bills when i submit

any idea how i can fix this?

答:
I couldnt figure out how this is possible with nested forms, so i set the entries which allready exists manually to the bill:</p>

```<code>nested_entries = {}
params[:bill][:entries_attributes] = {}

params[:entries].each_pair do |key, value|
   if value[:id].nil?
      params[:bill][:entries_attributes][key] = value
   else
     nested_entries[key] = value
   end
end

@bill = Bill.new(params[:bill])
@bill.save

bill_id = @bill.id

nested_entries.each_pair do |key, value|
   @entry = Entry.find(value[:id])
   value[:bill_id] = bill_id
   @entry.update_attributes(value)
end
</code>```

Title: update in nested_forms

Body:
Im using Rails 3.0.3

I have a Model Bill:

class Bill < ActiveRecord::Base
   has_many :entries
   accepts_nested_attributes_for :entries

end

In my Bill view i am using nested forms to create new entries in bills and with Javascript i insert existing entries with at this point, have no bill_id:

$("#row" + nested_form_id).append("<input type='hidden' name='bill[entries_attributes][" + nested_form_id + "][id]' id='bill_entries_attributes_" + nested_form_id + "_id' value='" + id +"' >");

when i submit the form i get this error:

ActiveRecord::RecordNotFound (Couldn't find Entry with ID=127 for Bill with ID=):
  app/controllers/bills_controller.rb:121:in `new'
  app/controllers/bills_controller.rb:121:in `create'

so the problem is, that rails is looking for the entry in bills when i submit

any idea how i can fix this?

Body:
I couldnt figure out how this is possible with nested forms, so i set the entries which allready exists manually to the bill:

nested_entries = {}
params[:bill][:entries_attributes] = {}

params[:entries].each_pair do |key, value|
   if value[:id].nil?
      params[:bill][:entries_attributes][key] = value
   else
     nested_entries[key] = value
   end
end

@bill = Bill.new(params[:bill])
@bill.save

bill_id = @bill.id

nested_entries.each_pair do |key, value|
   @entry = Entry.find(value[:id])
   value[:bill_id] = bill_id
   @entry.update_attributes(value)
end


问:
Chromedriver is blocking camera. Works only in first window
I need to run multiple Chrome windows, and in each I need to have camera working. Right now camera works only in first chrome window, and is blocked by this one in next windows. In second and next windows, even on webcamtests.com I have information that my camera is used in another application.

Everything works fine when I run Chrome manually. This issue appears only when I'm using webdriver (chromedriver)

I tried some chrome options like:

```<code>user-data-dir=/my_dir
disable-user-media-security
use-fake-ui-for-media-stream
</code>```

I tried even use-fake-device-for-media-stream - and it worked, but I need real camera. This option gave me fake animation.

My code right now:

```<code>ChromeOptions options = new ChromeOptions();
options.AddArguments("user-data-dir=/ChU/UDA30");
options.AddArguments("disable-infobars");
options.AddArguments("ignore-certificate-errors");
options.AddArguments("ignore-urlfetcher-cert-requests");
options.AddArguments("disable-user-media-security");
options.AddArguments("use-fake-ui-for-media-stream");
options.AddArguments("always-authorize-plugins");
var chromeDriverService = ChromeDriverService.CreateDefaultService();
chromeDriverService.HideCommandPromptWindow = true;
driver_a30 = new ChromeDriver(chromeDriverService, options);
</code>```

For every new window I have other user-data-dir.
I would like to have camera in every window, not only in first one.
Is there any solution for this?

答:
I've done some walkaround - maybe someone have the same problem as me:

Chrome is blocking webcam for new chromedriver.
So if I want to have webcam in many Chrome windows, I need to have only one chromedriver working at the same time.
So I'm running new Chrome windows on the same chromedriver, and then I have camera working everywhere.

Here's my code:

```<code>driver_chrome.SwitchTo().Window(driver_chrome.WindowHandles.First());
SendKeys.SendWait("^(n)");
System.Threading.Thread.Sleep(500);
driver_chrome.SwitchTo().Window(driver_chrome.WindowHandles.Last());
driver_chrome.Navigate().GoToUrl("URL");
</code>```

Body:
I need to run multiple Chrome windows, and in each I need to have camera working. Right now camera works only in first chrome window, and is blocked by this one in next windows. In second and next windows, even on webcamtests.com I have information that my camera is used in another application.

Everything works fine when I run Chrome manually. This issue appears only when I'm using webdriver (chromedriver)

I tried some chrome options like:

user-data-dir=/my_dir
disable-user-media-security
use-fake-ui-for-media-stream

I tried even use-fake-device-for-media-stream - and it worked, but I need real camera. This option gave me fake animation.

My code right now:

ChromeOptions options = new ChromeOptions();
options.AddArguments("user-data-dir=/ChU/UDA30");
options.AddArguments("disable-infobars");
options.AddArguments("ignore-certificate-errors");
options.AddArguments("ignore-urlfetcher-cert-requests");
options.AddArguments("disable-user-media-security");
options.AddArguments("use-fake-ui-for-media-stream");
options.AddArguments("always-authorize-plugins");
var chromeDriverService = ChromeDriverService.CreateDefaultService();
chromeDriverService.HideCommandPromptWindow = true;
driver_a30 = new ChromeDriver(chromeDriverService, options);

For every new window I have other user-data-dir.
I would like to have camera in every window, not only in first one.
Is there any solution for this?

Body:
I've done some walkaround - maybe someone have the same problem as me:

Chrome is blocking webcam for new chromedriver.
So if I want to have webcam in many Chrome windows, I need to have only one chromedriver working at the same time.
So I'm running new Chrome windows on the same chromedriver, and then I have camera working everywhere.

Here's my code:

driver_chrome.SwitchTo().Window(driver_chrome.WindowHandles.First());
SendKeys.SendWait("^(n)");
System.Threading.Thread.Sleep(500);
driver_chrome.SwitchTo().Window(driver_chrome.WindowHandles.Last());
driver_chrome.Navigate().GoToUrl("URL");


问:
Hamming Filter in Frequency and Spatial Domain
I want to remove the Gibbs artifact in a 1D signal by applying the Hamming filter on that in MATLAB.

What I have is the k1 which is the signal in frequency domain. I can get the signal in time domain by applying DFT on k1:

s1 = ifft(ifftshift(k1));

This signal has Gibbs artifact. Now, I want to remove it by (A) multiplying Hamming filter to k1 in teh frequency domain and (B) convolving IFFT of Hamming filter with s1 in the spatial domain. I am expecting same output from both of these:

```<code>% (A) Multiplying Hamming filter to `k1`
n = size(k1,2);
wk = hamming(n,'symmetric')';
k2 = wk.*k1;
s2 = ifft(ifftshift(k2));

% (B) Convolving IFFT of Hamming filter with `s1`
wx = ifft(ifftshift(wk));
s3 = conv(s1,wx,'same');
</code>```

The result of (A), s2, seems to be correct since the signal looks blurred and the Gibbs artifact is gone. However, the result of (B), s3, is completely different and incorrect. What is missing in (B)? (Please download k1.mat from this link if you need it.)

答:
From the data you posted what you call "Gibbs" on space are high frequency components on frequency. When you multiply your hamming window in frequency in fact you are smoothing those higher frequencies. They are in the borders (negative and positive) of your complex array k1.

Bellow is what happens when you make k2 = wk.*k1;

That's why your so called space "Gibbs" is gone.

This is not a stander use of a Hamming window that is commonly applied on time|space to reduce Gibb's on frequency when clipping and sampling a signal, function or filter kernel on time|space.

To reproduce it in space you would have to design a very smooth low pass filter that gives the hamming window response in frequency to make that convolution. I don't recall the inverse transform of a Hamming Window but you could use a gaussian filter.

Btw wx = ifft(ifftshift(wk)); gives a wx  not symmetric with respect to its maximum.

Body:
I want to remove the Gibbs artifact in a 1D signal by applying the Hamming filter on that in MATLAB.

What I have is the k1 which is the signal in frequency domain. I can get the signal in time domain by applying DFT on k1:

s1 = ifft(ifftshift(k1));

This signal has Gibbs artifact. Now, I want to remove it by (A) multiplying Hamming filter to k1 in teh frequency domain and (B) convolving IFFT of Hamming filter with s1 in the spatial domain. I am expecting same output from both of these:

% (A) Multiplying Hamming filter to `k1`
n = size(k1,2);
wk = hamming(n,'symmetric')';
k2 = wk.*k1;
s2 = ifft(ifftshift(k2));

% (B) Convolving IFFT of Hamming filter with `s1`
wx = ifft(ifftshift(wk));
s3 = conv(s1,wx,'same');

The result of (A), s2, seems to be correct since the signal looks blurred and the Gibbs artifact is gone. However, the result of (B), s3, is completely different and incorrect. What is missing in (B)? (Please download k1.mat from this link if you need it.)


问:
How to create custom tag's archive page for custom post type?
When i add custom tag to custom post type, the archive page doesn't work.

taxonomy-tags.php has been added,here is some of my code:

function create_taxonomies_tag() {
        $labels = array(
            'name'              => _x( '新标签', 'taxonomy 名称' ),
            'singular_name'     => _x( '新标签', 'taxonomy 单数名称' ),
            'search_items'      => __( '搜索新标签' ),
            'all_items'         => __( '所有新标签' ),
            'parent_item'       => __( '该新标签的上级分类' ),
            'parent_item_colon' => __( '该新标签的上级分类：' ),
            'edit_item'         => __( '编辑新标签' ),
            'update_item'       => __( '更新新标签' ),
            'add_new_item'      => __( '添加新的新标签' ),
            'new_item_name'     => __( '新的标签' ),
            'menu_name'         => __( '新标签' ),
        );
        $args = array(
            'hierarchical'      => false,
            'labels'            => $labels,
            'show_ui'           => true,
            'show_admin_column' => true,
            'query_var'         => true,
            'rewrite'           => array( 'slug' => tags ),
        );
        register_taxonomy( 'tags', array('site'), $args );
    }

```

what should i  do to fix it? please help me,thanks

答: Give a try to Toolset Types plugin, can give you some guide about this and help enabling what you need.</p>

Body:
When i add custom tag to custom post type, the archive page doesn't work.

taxonomy-tags.php has been added,here is some of my code:

function create_taxonomies_tag() {
        $labels = array(
            'name'              => _x( '新标签', 'taxonomy 名称' ),
            'singular_name'     => _x( '新标签', 'taxonomy 单数名称' ),
            'search_items'      => __( '搜索新标签' ),
            'all_items'         => __( '所有新标签' ),
            'parent_item'       => __( '该新标签的上级分类' ),
            'parent_item_colon' => __( '该新标签的上级分类：' ),
            'edit_item'         => __( '编辑新标签' ),
            'update_item'       => __( '更新新标签' ),
            'add_new_item'      => __( '添加新的新标签' ),
            'new_item_name'     => __( '新的标签' ),
            'menu_name'         => __( '新标签' ),
        );
        $args = array(
            'hierarchical'      => false,
            'labels'            => $labels,
            'show_ui'           => true,
            'show_admin_column' => true,
            'query_var'         => true,
            'rewrite'           => array( 'slug' => tags ),
        );
        register_taxonomy( 'tags', array('site'), $args );
    }

what should i  do to fix it? please help me,thanks


Title: How to post the nested dictionary as JSON body using swift

Body:
{
    "data": [{
        "_id": "1558946471217677c352281",
        "title": "ssds",
        "user_id": "",
        "user_name": "",
        "checklist": {
            "id": "5ccad234e47ab8565a45b6a2",
            "name": "task edited 2"
        },
        "idc": "5ccad234e47ab8565a45b6a2",
        "completed": 0,
        "created": "2019-05-27T22:41:11+14:00",
        "tps": 1,
        "tpe": 0
    }],
    "tz": "2d626e1289dafb70b0e890eb97bf5c4910b0a47edad9624b5973cdb244abe8fed5e6",
    "uID": "7c24d0c8c6034017556946c418bbf0b182ba6a0a62230a860c3319c8f137c06920da465df3d789d1"
}

Body:
You can prepare your dictionary format as follows:

let checklist = [
    "id": "5ccad234e47ab8565a45b6a2",
    "name": "task edited 2"
]

let data = [
        [
        "_id": "1558946471217677c352281",
        "title": "ssds",
        "user_id": "",
        "user_name": "",
        "checklist": "",
        "idc": "5ccad234e47ab8565a45b6a2",
        "completed": 0,
        "created": "2019-05-27T22:41:11+14:00",
        "tps": 1,
        "tpe": 0
        ],
        [
            "_id": "1558946471217677c352281",
            "title": "Abcd",
            "user_id": "",
            "user_name": "",
            "checklist": "",
            "idc": "5ccad234e47ab8565a45b6a2",
            "completed": 0,
            "created": "2019-05-27T22:41:11+15:00",
            "tps": 1,
            "tpe": 0
        ]
        ] as [[String : Any]]

let paramDict = [
    "data": [data],
    "tz":"2d626e1289dafb70b0e890eb97bf5c4910b0a47edad9624b5973cdb244abe8fed5e6",
    "uID":"7c24d0c8c6034017556946c418bbf0b182ba6a0a62230a860c3319c8f137c06920da465df3d789d1"
    ] as [String : Any]


问:
How to get last inserted id?
I have this code:

```<code>string insertSql =
    "INSERT INTO aspnet_GameProfiles(UserId,GameId) VALUES(@UserId, @GameId)";

using (SqlConnection myConnection = new SqlConnection(myConnectionString))
{
   myConnection.Open();

   SqlCommand myCommand = new SqlCommand(insertSql, myConnection);

   myCommand.Parameters.AddWithValue("@UserId", newUserId);
   myCommand.Parameters.AddWithValue("@GameId", newGameId);

   myCommand.ExecuteNonQuery();

   myConnection.Close();
}
</code>```

When I insert into this table, I have an auto_increment int primary key column called GamesProfileId, how can i get the last inserted one after this so I can use that id to insert into another table?

答:
I had the same need and found this answer ..

This creates a record in the company table (comp), it the grabs the auto ID created on the company table and drops that into a Staff table (staff) so the 2 tables can be linked, MANY staff to ONE company. It works on my SQL 2008 DB, should work on SQL 2005 and above.

===========================

```<code>CREATE PROCEDURE [dbo].[InsertNewCompanyAndStaffDetails]

 @comp_name varchar(55) = 'Big Company',

 @comp_regno nchar(8) = '12345678',

 @comp_email nvarchar(50) = 'no1@home.com',

 @recID INT OUTPUT
</code>```

-- The '@recID' is used to hold the Company auto generated ID number that we are about to grab

```<code>AS
 Begin

  SET NOCOUNT ON

  DECLARE @tableVar TABLE (tempID INT)
</code>```

-- The line above is used to create a tempory table to hold the auto generated ID number for later use. It has only one field 'tempID' and its type INT is the same as the '@recID'.

```<code>  INSERT INTO comp(comp_name, comp_regno, comp_email)

  OUTPUT inserted.comp_id INTO @tableVar
</code>```

-- The 'OUTPUT inserted.' line above is used to grab data out of any field in the record it is creating right now. This data we want is the ID autonumber. So make sure it says the correct field name for your table, mine is 'comp_id'. This is then dropped into the tempory table we created earlier.

```<code>  VALUES (@comp_name, @comp_regno, @comp_email)

  SET @recID = (SELECT tempID FROM @tableVar)
</code>```

-- The line above is used to search the tempory table we created earlier where the ID we need is saved. Since there is only one record in this tempory table, and only one field, it will only select the ID number you need and drop it into '@recID'. '@recID' now has the ID number you want and you can use it how you want like i have used it below.

```<code>  INSERT INTO staff(Staff_comp_id)
  VALUES (@recID)

 End
</code>```

-- So there you go. You can actually grab what ever you want in the 'OUTPUT inserted.WhatEverFieldNameYouWant' line and create what fields you want in your tempory table and access it to use how ever you want.

I was looking for something like this for ages, with this detailed break down, I hope this helps.

ContentLicense: CC BY-SA 2.5

Title: How to get last inserted id?

Body:
I have this code:

string insertSql =
    "INSERT INTO aspnet_GameProfiles(UserId,GameId) VALUES(@UserId, @GameId)";

using (SqlConnection myConnection = new SqlConnection(myConnectionString))
{
   myConnection.Open();

   SqlCommand myCommand = new SqlCommand(insertSql, myConnection);

   myCommand.Parameters.AddWithValue("@UserId", newUserId);
   myCommand.Parameters.AddWithValue("@GameId", newGameId);

   myCommand.ExecuteNonQuery();

   myConnection.Close();
}

When I insert into this table, I have an auto_increment int primary key column called GamesProfileId, how can i get the last inserted one after this so I can use that id to insert into another table?

Body:
I had the same need and found this answer ..

This creates a record in the company table (comp), it the grabs the auto ID created on the company table and drops that into a Staff table (staff) so the 2 tables can be linked, MANY staff to ONE company. It works on my SQL 2008 DB, should work on SQL 2005 and above.

===========================

CREATE PROCEDURE [dbo].[InsertNewCompanyAndStaffDetails]

 @comp_name varchar(55) = 'Big Company',

 @comp_regno nchar(8) = '12345678',

 @comp_email nvarchar(50) = 'no1@home.com',

 @recID INT OUTPUT

-- The '@recID' is used to hold the Company auto generated ID number that we are about to grab

AS
 Begin

  SET NOCOUNT ON

  DECLARE @tableVar TABLE (tempID INT)

-- The line above is used to create a tempory table to hold the auto generated ID number for later use. It has only one field 'tempID' and its type INT is the same as the '@recID'.

  INSERT INTO comp(comp_name, comp_regno, comp_email)

  OUTPUT inserted.comp_id INTO @tableVar

-- The 'OUTPUT inserted.' line above is used to grab data out of any field in the record it is creating right now. This data we want is the ID autonumber. So make sure it says the correct field name for your table, mine is 'comp_id'. This is then dropped into the tempory table we created earlier.

  VALUES (@comp_name, @comp_regno, @comp_email)

  SET @recID = (SELECT tempID FROM @tableVar)

-- The line above is used to search the tempory table we created earlier where the ID we need is saved. Since there is only one record in this tempory table, and only one field, it will only select the ID number you need and drop it into '@recID'. '@recID' now has the ID number you want and you can use it how you want like i have used it below.

  INSERT INTO staff(Staff_comp_id)
  VALUES (@recID)

 End

-- So there you go. You can actually grab what ever you want in the 'OUTPUT inserted.WhatEverFieldNameYouWant' line and create what fields you want in your tempory table and access it to use how ever you want.

I was looking for something like this for ages, with this detailed break down, I hope this helps.


问:
How do I insert .html file in adobe captivate?
I am unable to insert a video which is having table of contents and is capable of playing at required time frame and that particular video is supposed to be a part of adobe captivate project. The video is embedded in a html5 file. Adding a zip file of the html5 file along with xml etc. is unable to load in Adobe Captivate. Please if someone can help me proceed further.</p>

答:
You cannot insert HTML files, but you can insert a web object !

So you just have to publish your video on a server, to copy the link address where it is located on the internet and to insert this link in Adobe Captivate ( insert > objects > web).

Hope it will help you.


问:
use an attribute outside from forkJoin
I have the list cardsbackground that contains the name of images, to get the images i have an api that has as parameters certificate number and image name

I want to dislay the images that matches the names that are in the list cardsbackground

The problem is that forkJoin returns the list of images and i want to display for each image its name

When i want to display the name inside the subscribe, it displays nothing

```<code>forkJoin(
    this.cardsBackground.map(
        (name, index) => this.cardBackgroundService.getImage(certificateNumber, name)
    )
).subscribe(
    data => data.forEach(element => console.log(name + " - " + element))
);
</code>```

答:
You define the name variable inside the scope of your map function, which makes it unaccessable inside the subscription scope.

An easy way would be to pipe the service call and return a new object with both the name and the result to be accessed later.

```<code>forkJoin(
    this.cardsBackground.map(
      (name, index) => this.cardBackgroundService.getImage(certificateNumber, name).pipe(
        map(image => ({
          name: name,
          image: image
        }))
      )
    )
).subscribe(data => data.forEach(element => console.log(element.name + " - " + element)));
</code>```

Title: use an attribute outside from forkJoin

Body:
I have the list cardsbackground that contains the name of images, to get the images i have an api that has as parameters certificate number and image name

I want to dislay the images that matches the names that are in the list cardsbackground

The problem is that forkJoin returns the list of images and i want to display for each image its name

When i want to display the name inside the subscribe, it displays nothing

forkJoin(
    this.cardsBackground.map(
        (name, index) => this.cardBackgroundService.getImage(certificateNumber, name)
    )
).subscribe(
    data => data.forEach(element => console.log(name + " - " + element))
);

Body:
You define the name variable inside the scope of your map function, which makes it unaccessable inside the subscription scope.

An easy way would be to pipe the service call and return a new object with both the name and the result to be accessed later.

forkJoin(
    this.cardsBackground.map(
      (name, index) => this.cardBackgroundService.getImage(certificateNumber, name).pipe(
        map(image => ({
          name: name,
          image: image
        }))
      )
    )
).subscribe(data => data.forEach(element => console.log(element.name + " - " + element)));


问:
Source of Img should be dynamic
how can i load an img src dynamic with React ?
I tried the following:

```<code> const country = this.state.countryCode;
 <img src="https://www.countryflags.io/"+country+"/shiny/64.png"/>
</code>```

But i got the error:

Parsing error: Unexpected token

答:
This isn't React-specific, it's because you have the + in the src.

Use a string template literal with back-ticks:

src=`https://www.countryflags.io/${country}/shiny/64.png`

Title: Source of Img should be dynamic

Body:
how can i load an img src dynamic with React ?
I tried the following:

 const country = this.state.countryCode;

But i got the error:

Parsing error: Unexpected token


问:
How to listen for a WebView finishing loading a URL?
I have a WebView that is loading a page from the Internet. I want to show a ProgressBar until the loading is complete.

How do I listen for the completion of page loading of a WebView?

答:
for Kotlin users:

```<code>webView.webViewClient = object : WebViewClient() {
            override fun onPageFinished(view: WebView?, url: String?) {
                // do your logic
            }
        }
</code>```

there are a lot of methods that you can override though

Body:
for Kotlin users:

webView.webViewClient = object : WebViewClient() {
            override fun onPageFinished(view: WebView?, url: String?) {
                // do your logic
            }
        }

there are a lot of methods that you can override though


问:
How to deserialize JSON to a derived class using c#
I am trying to map the json response.

I have below json reponse code

```<code>string JSON = await SendGraphRequest("/users/", $"$filter=signInNames/any(x:x/value eq '{username}')", null, HttpMethod.Get);
</code>```

this the json response

```<code>{
  "extension_7182f7a071344106a9e47cc960ab93e8_DOB": null,
  "extension_7182f7a071344106a9e47cc960ab93e8_middleName": null,
  "objectID": "",
  "accountEnabled": true,
  "email": Test
  }
</code>```

I want to deSerialize the json response, by using below code

```<code>var graphUserRespModel =  JsonConvert.DeserializeObject<ResponseModelPrime>(JSON);
</code>```

I am using the three classes for DeserializeObject But i am getting the null value on all the fields. please let me know what mistake my doing.

```<code> public class ResponseModelPrime
    {

        [JsonProperty(PropertyName = "odata.metadata")]
        public string OdataMetadata { get; set; }

        [JsonProperty(PropertyName = "Status")]
        public StatusModel Status { get; set; }

        [JsonProperty(PropertyName = "objectId")]
        public string ObjectId { get; set; }

        [JsonProperty(PropertyName = "email")]
        public string Email { get; set; }

        [JsonProperty(PropertyName = "accountEnabled")]
        public bool AccountEnabled { get; set; }

        [JsonProperty(PropertyName = "DOB")]
        public string DOB { get; set; }

        [JsonProperty(PropertyName = "middleName")]
        public string middleName { get; set; }

}

 public class ResponseModel
    {

        [JsonProperty(PropertyName = "objectId")]
        public string ObjectId { get; set; }

        [JsonProperty(PropertyName = "email")]
        public string Email { get; set; }

        [JsonProperty(PropertyName = "accountEnabled")]
        public bool AccountEnabled { get; set; }
}

public  class ResponseModelSIT : ResponseModel
    {
        [JsonProperty(PropertyName = "extension_7182f7a071344106a9e47cc960ab93e8_DOB")]
        public string extension_7182f7a071344106a9e47cc960ab93e8_DOB { get; set; }

        [JsonProperty(PropertyName = "extension_7182f7a071344106a9e47cc960ab93e8_middleName")]
        public string extension_7182f7a071344106a9e47cc960ab93e8_middleName { get; set; }

        }
</code>```

答:
For deserializing json, you need to go in a simple way...

```<code>public Form1()
        {
            InitializeComponent();

            try
            {

            var json = @"{
                          'extension_7182f7a071344106a9e47cc960ab93e8_DOB': '17/12/1995',
                          'extension_7182f7a071344106a9e47cc960ab93e8_middleName': 'Roger',
                          'objectID': '',
                          'accountEnabled': true,
                          'email': 'Test'
                         }";

                var items = JsonConvert.DeserializeObject<ResponseModelPrime>(json);

            }
            catch (Exception ex)
            {
                var exception = ex;
            }
        }
        public class ResponseModelPrime
        {
            [JsonProperty(PropertyName = "odata.metadata")]
            public string OdataMetadata { get; set; }

            [JsonProperty(PropertyName = "objectId")]
            public string ObjectId { get; set; }

            [JsonProperty(PropertyName = "email")]
            public string Email { get; set; }

            [JsonProperty(PropertyName = "accountEnabled")]
            public bool AccountEnabled { get; set; }

            [JsonProperty(PropertyName = "DOB")]
            public string DOB { get; set; }

            [JsonProperty(PropertyName = "middleName")]
            public string middleName { get; set; }

            [JsonProperty(PropertyName = "extension_7182f7a071344106a9e47cc960ab93e8_DOB")]
            public string extension_7182f7a071344106a9e47cc960ab93e8_DOB { get; set; }

            [JsonProperty(PropertyName = "extension_7182f7a071344106a9e47cc960ab93e8_middleName")]
            public string extension_7182f7a071344106a9e47cc960ab93e8_middleName { get; set; }
        }
</code>```

Body:
I am trying to map the json response.

I have below json reponse code

string JSON = await SendGraphRequest("/users/", $"$filter=signInNames/any(x:x/value eq '{username}')", null, HttpMethod.Get);

this the json response

{
  "extension_7182f7a071344106a9e47cc960ab93e8_DOB": null,
  "extension_7182f7a071344106a9e47cc960ab93e8_middleName": null,
  "objectID": "",
  "accountEnabled": true,
  "email": Test
  }

I want to deSerialize the json response, by using below code

var graphUserRespModel =  JsonConvert.DeserializeObject<ResponseModelPrime>(JSON);

I am using the three classes for DeserializeObject But i am getting the null value on all the fields. please let me know what mistake my doing.

 public class ResponseModelPrime
    {

        [JsonProperty(PropertyName = "odata.metadata")]
        public string OdataMetadata { get; set; }

        [JsonProperty(PropertyName = "Status")]
        public StatusModel Status { get; set; }

        [JsonProperty(PropertyName = "objectId")]
        public string ObjectId { get; set; }

        [JsonProperty(PropertyName = "email")]
        public string Email { get; set; }

        [JsonProperty(PropertyName = "accountEnabled")]
        public bool AccountEnabled { get; set; }

        [JsonProperty(PropertyName = "DOB")]
        public string DOB { get; set; }

        [JsonProperty(PropertyName = "middleName")]
        public string middleName { get; set; }

}

 public class ResponseModel
    {

        [JsonProperty(PropertyName = "objectId")]
        public string ObjectId { get; set; }

        [JsonProperty(PropertyName = "email")]
        public string Email { get; set; }

        [JsonProperty(PropertyName = "accountEnabled")]
        public bool AccountEnabled { get; set; }
}

public  class ResponseModelSIT : ResponseModel
    {
        [JsonProperty(PropertyName = "extension_7182f7a071344106a9e47cc960ab93e8_DOB")]
        public string extension_7182f7a071344106a9e47cc960ab93e8_DOB { get; set; }

        [JsonProperty(PropertyName = "extension_7182f7a071344106a9e47cc960ab93e8_middleName")]
        public string extension_7182f7a071344106a9e47cc960ab93e8_middleName { get; set; }

        }

Body:
For deserializing json, you need to go in a simple way...

public Form1()
        {
            InitializeComponent();

            try
            {

            var json = @"{
                          'extension_7182f7a071344106a9e47cc960ab93e8_DOB': '17/12/1995',
                          'extension_7182f7a071344106a9e47cc960ab93e8_middleName': 'Roger',
                          'objectID': '',
                          'accountEnabled': true,
                          'email': 'Test'
                         }";

                var items = JsonConvert.DeserializeObject<ResponseModelPrime>(json);

            }
            catch (Exception ex)
            {
                var exception = ex;
            }
        }
        public class ResponseModelPrime
        {
            [JsonProperty(PropertyName = "odata.metadata")]
            public string OdataMetadata { get; set; }

            [JsonProperty(PropertyName = "objectId")]
            public string ObjectId { get; set; }

            [JsonProperty(PropertyName = "email")]
            public string Email { get; set; }

            [JsonProperty(PropertyName = "accountEnabled")]
            public bool AccountEnabled { get; set; }

            [JsonProperty(PropertyName = "DOB")]
            public string DOB { get; set; }

            [JsonProperty(PropertyName = "middleName")]
            public string middleName { get; set; }

            [JsonProperty(PropertyName = "extension_7182f7a071344106a9e47cc960ab93e8_DOB")]
            public string extension_7182f7a071344106a9e47cc960ab93e8_DOB { get; set; }

            [JsonProperty(PropertyName = "extension_7182f7a071344106a9e47cc960ab93e8_middleName")]
            public string extension_7182f7a071344106a9e47cc960ab93e8_middleName { get; set; }
        }


问:
Vector option in Java
I am using vector of object. My issue is the removal from vector is expensive operation( O(n^2)). What would be the replacement of vector in Java. In my uses addition and removal is extensively happens.

i am C++ person don't know much Java

答:
Check out this article:

http://www.javaworld.com/javaworld/javaqa/2001-06/03-qa-0622-vector.html

LinkedList can add/remove items at O(1)

Title: Vector option in Java


问:
Clob Data filed replacement issue in Oracle
my Input string

```<code>Employee[10|||Aryan|||CA|||USA|||URBAN|||IT
ENGINEER+++20|||Arjun|||FA|||USA|||RULER|||DEVELOPER]
</code>```

My output should be

```<code>[
 {Employee Name : Aryan,Employee ID:10,Emploee Role:IT ENGINEER}
   ,
 {Employee Name : Arjun,Employee ID:20,Emploee Role:DEVELOPER}
]
</code>```

I tried multiple scenarios which are not working as expected

答:
The following query will work for any number of entries.

```<code>SELECT
    '['
    || CHR(10)
    || RTRIM(XMLAGG(XMLELEMENT(E, INDVDL_ENTITY, CHR(10)
                                                 || ','
                                                 || CHR(10)).EXTRACT('//text()')
        ORDER BY
            L
    ).GETCLOBVAL(), CHR(10)
                    || ','
                    || CHR(10))
    || CHR(10)
    || ']'
FROM
    (
        SELECT
            '{Employee Name : '
            || REGEXP_SUBSTR(INDVDL_ENTITY, '[^(/|/|/|)]+', 1, 2)
            || ',Employee ID:'
            || REGEXP_SUBSTR(INDVDL_ENTITY, '[^(/|/|/|)]+', 1, 1)
            || ',Emploee Role:'
            || REGEXP_SUBSTR(INDVDL_ENTITY, '[^(/|/|/|)]+', 1, 6)
            || '}' AS INDVDL_ENTITY,
            L   AS L
        FROM
            (
                SELECT
                    REGEXP_SUBSTR(VAL, '[^\+\+\+]+', 1, LEVEL) AS INDVDL_ENTITY,
                    LEVEL   AS L
                FROM
                    (
                        SELECT
                            TRIM(TRAILING ']' FROM REGEXP_SUBSTR('Employee[10|||Aryan|||CA|||USA|||URBAN|||IT ENGINEER+++20|||Arjun|||FA|||USA|||RULER|||DEVELOPER]'
                            , '[^\[]+', 1, 2)) AS VAL
                        FROM
                            DUAL
                    )
                CONNECT BY
                    ( REGEXP_COUNT(VAL, '\+\+\+') + 1 ) >= LEVEL
            )
    );
</code>```

The output of the query:

```<code>[
{Employee Name : Aryan,Employee ID:10,Emploee Role:IT ENGINEER}
,
{Employee Name : Arjun,Employee ID:20,Emploee Role:DEVELOPER}
]
</code>```

Feel free to add as many entries as you want into your input string. (I have tested it with five entries also, It is working fine)  :) :)

As suggested by Shaun, create your own formatting using CHR function.

Thanks.

Body:
my Input string

Employee[10|||Aryan|||CA|||USA|||URBAN|||IT
ENGINEER+++20|||Arjun|||FA|||USA|||RULER|||DEVELOPER]

My output should be

[
 {Employee Name : Aryan,Employee ID:10,Emploee Role:IT ENGINEER}
   ,
 {Employee Name : Arjun,Employee ID:20,Emploee Role:DEVELOPER}
]

I tried multiple scenarios which are not working as expected

Body:
The following query will work for any number of entries.

SELECT
    '['
    || CHR(10)
    || RTRIM(XMLAGG(XMLELEMENT(E, INDVDL_ENTITY, CHR(10)
                                                 || ','
                                                 || CHR(10)).EXTRACT('//text()')
        ORDER BY
            L
    ).GETCLOBVAL(), CHR(10)
                    || ','
                    || CHR(10))
    || CHR(10)
    || ']'
FROM
    (
        SELECT
            '{Employee Name : '
            || REGEXP_SUBSTR(INDVDL_ENTITY, '[^(/|/|/|)]+', 1, 2)
            || ',Employee ID:'
            || REGEXP_SUBSTR(INDVDL_ENTITY, '[^(/|/|/|)]+', 1, 1)
            || ',Emploee Role:'
            || REGEXP_SUBSTR(INDVDL_ENTITY, '[^(/|/|/|)]+', 1, 6)
            || '}' AS INDVDL_ENTITY,
            L   AS L
        FROM
            (
                SELECT
                    REGEXP_SUBSTR(VAL, '[^\+\+\+]+', 1, LEVEL) AS INDVDL_ENTITY,
                    LEVEL   AS L
                FROM
                    (
                        SELECT
                            TRIM(TRAILING ']' FROM REGEXP_SUBSTR('Employee[10|||Aryan|||CA|||USA|||URBAN|||IT ENGINEER+++20|||Arjun|||FA|||USA|||RULER|||DEVELOPER]'
                            , '[^\[]+', 1, 2)) AS VAL
                        FROM
                            DUAL
                    )
                CONNECT BY
                    ( REGEXP_COUNT(VAL, '\+\+\+') + 1 ) >= LEVEL
            )
    );

The output of the query:

[
{Employee Name : Aryan,Employee ID:10,Emploee Role:IT ENGINEER}
,
{Employee Name : Arjun,Employee ID:20,Emploee Role:DEVELOPER}
]

Feel free to add as many entries as you want into your input string. (I have tested it with five entries also, It is working fine)  :) :)

As suggested by Shaun, create your own formatting using CHR function.

Thanks.


问:
How to reset Visual Studio Code key bindings?
I have been experimenting with my vs-code key bindings.

I would like to reset the key-bindings to the original settings.

How do I do that?

I am on Linux Mint 18.

I tried removing all the records from the keybindings.json

答:
Version 1.34.0 seems to have the settings at a slightly different location:

Click File > Preferences > Keyboard Shortcuts

There is a triple-dot (...) at the top-right hand corner. Click on that and select "Show User Keybindings"

Right click on the key-binding that you want to reset and choose "Reset Keybinding"


问:
set favicon to maven-javadoc-plugin generated javadoc file
I can set window title using following code in "maven-java doc-plugin".

```<code><configuration>
     <windowtitle>name</windowtitle>
</configuration>
</code>```

but I  cannot set "favicon" to my java doc

答:
I saw your question and found the following is my observation.

First of all, there isn't any ready-made solution in maven-javadoc-plugin which will allow you to add a custom favicon.ico in your Javadoc.

But the good thing is:

I also found out that in maven-javadoc-plugin you can modify it to use your custom doclet implementation for generating Javadocs.

Now, what is doclet (More details here)?

From the above link,

Javadoc Doclets
You can customize the content and format of the Javadoc tool's output by usingdoclets. The Javadoc tool has a default "built-in"doclet, called the standarddoclet, that generates HTML-formatted API documentation. You can modify or subclass the standarddoclet, or write your owndocletto generate HTML, XML, MIF, RTF or whatever output format you'd like

So basically you can customize what your Javadoc can generate, you can use more information on customizing the doclet in below mentioned links.

Information about which class to modify to generate custom Javadocs.

Once you customize the doclet, then you can use it in your maven-javadoc-plugin as mentioned here.

I hope this helps.

Body:
I can set window title using following code in "maven-java doc-plugin".

<configuration>
     <windowtitle>name</windowtitle>
</configuration>

but I  cannot set "favicon" to my java doc


问:
Identify Current view controller from PopUp view controller in swift
Assume that we have 2 view controllers

FirstViewController.swift

PopUpViewContraller.swift

PopUpViewContraller has been loaded on FirstViewController. Now how can I call a function in the FirstViewController from PopUpViewContraller.

答:
Thank you for answer my question.

Finally, I got the solution for the above question.

We can solve this problem using notification center.

1) In the popup view controller ()

```<code>NotificationCenter.default.post(name: NSNotification.Name(rawValue: "botIsRemoved"), object: self)
</code>```

2) In the first view controller

inside viewDidLoard()

```<code>NotificationCenter.default.addObserver(self, selector: #selector(removeBotNow), name: NSNotification.Name(rawValue: "botIsRemoved"), object: nil)
</code>```

and add the following function

```<code>@objc func removeBotNow(notification : Notification){

        // your tasks

    }
</code>```

Body:
Thank you for answer my question.

Finally, I got the solution for the above question.

We can solve this problem using notification center.

1) In the popup view controller ()

NotificationCenter.default.post(name: NSNotification.Name(rawValue: "botIsRemoved"), object: self)

2) In the first view controller

inside viewDidLoard()

NotificationCenter.default.addObserver(self, selector: #selector(removeBotNow), name: NSNotification.Name(rawValue: "botIsRemoved"), object: nil)

and add the following function

@objc func removeBotNow(notification : Notification){

        // your tasks

    }


问:
Use Swashbuckle to get one OpenAPI document from multiple .NET Core projects
Is there a way to get a single OpenAPI document containing all operations from multiple .NET core projects using Swashbuckle?

Context:

We have multiple frontdoor projects (built with .NET Core) but they are semantically a part of one service, for which we want to have a single OpenAPI document. Since Swashbuckle generates the document at start up for each individual project, we end up with multiple OpenAPI documents.

Is there a workaround to get these operations to show up under one document? From the way Swashbuckle works, it seems like this would not be possible? We can probably combine the Swagger documents later on with other libraries, but if Swashbuckle has a way to support this, we would prefer that.

答:
Probably you have to use an api gateway.

Actually there are multiple commercial product that offer this service, like:

Apigee

AWS API Gateway

Azure API Management

but if you don't want to use (and pay) for these services, you can use an open source alternative for .Net Core like Ocelot

With API Gateway you'll be able to merge multiple api project, and menage their use and distribution (eg. security policy, throttling, etc..).


问:
Preg_match(_all) can't collect some data from Google
I'm creating a tool for my websites to see what position they are in Google on different keywords.

Now, I want to collect this part of their sourcecode:

```<code><a href="http://www.test.com/" class=l onmousedown="return clk(this.href,'','','','1','','0CBoQFjAA')">Linktitle in Google!</a>
</code>```

The problem is that the preg_match OR preg_match_all function doesn't match "onmousedown" or "this.href" or the ,'1' part of the link. And that is exactly the part i need...

Does anyone has an idea why this is, and more important.. how to solve this???

The code I use is obvious.. i even tried to use "/onmousedown/" or "/\'1\'/" but it didn't help.

Thank you very much!!!!

答:
According to Google, you are not allowed to scrape their website.

Their robot.txt is here: http://www.google.com/robots.txt.

That said, it's a bit hypocritical coming from a company whose whole business model is to scrape other people's websites.

Consider yourself warned.

The regex is simple:

```<code><a [^<]*class=l.*?</a>
</code>```

Now, for the folks who claim that HTML can not be parsed with regex... yes, you are right, you can not parse html in regex. But let's not be ridiculous here.

Extracting a specific block of text from an HTML page with a known format is definitely possible (and easy) to do in regex. That's what regex is for.

This is not "parsing HTML", and in a case such as this one, where the format is known and the application non-critical, regex does just fine.

I just checked and there is an API from Google which allows you to make up to 100 queries for free on a custom search engine.
http://www.google.com/cse/
https://code.google.com/apis/console/?api=customsearch&pli=1#welcome

It requires a Google account and an API key, which you can get at the links above.

Warning, wadding through the legalese is going to be considerably harder than writing your scraper

Body:
I'm creating a tool for my websites to see what position they are in Google on different keywords.

Now, I want to collect this part of their sourcecode:

Linktitle in Google!

The problem is that the preg_match OR preg_match_all function doesn't match "onmousedown" or "this.href" or the ,'1' part of the link. And that is exactly the part i need...

Does anyone has an idea why this is, and more important.. how to solve this???

The code I use is obvious.. i even tried to use "/onmousedown/" or "/\'1\'/" but it didn't help.

Thank you very much!!!!

Body:
According to Google, you are not allowed to scrape their website.

Their robot.txt is here: http://www.google.com/robots.txt.

That said, it's a bit hypocritical coming from a company whose whole business model is to scrape other people's websites.

Consider yourself warned.

The regex is simple:

<a [^<]*class=l.*?</a>

Now, for the folks who claim that HTML can not be parsed with regex... yes, you are right, you can not parse html in regex. But let's not be ridiculous here.

Extracting a specific block of text from an HTML page with a known format is definitely possible (and easy) to do in regex. That's what regex is for.

This is not "parsing HTML", and in a case such as this one, where the format is known and the application non-critical, regex does just fine.

I just checked and there is an API from Google which allows you to make up to 100 queries for free on a custom search engine.
http://www.google.com/cse/
https://code.google.com/apis/console/?api=customsearch&pli=1#welcome

It requires a Google account and an API key, which you can get at the links above.

Warning, wadding through the legalese is going to be considerably harder than writing your scraper


问:
How to remove empty strings from the end of a list of strings (only at the end)
i have some list of strings. I want to remove empty strings from the end of the list (i.e.  each list should end with a non empty element).

```<code>input
list1= ['a1','b1','c1','d1','']
list2 = ['a2','','b2','','c2','d2','']
list3 = ['a3','','b3','','','']
list4 = ['','','','','']
</code>```

output

```<code>list1= ['a1','b1','c1','d1']
list2 = ['a2','','b2','','c2','d2']
list3 = ['a3','','b3']
list4 = ['']
</code>```

if all the elements are empty strings , only one empty string should remain (eg. list4).

答:
The easiest way (in my opinion)

def remove_empty_at_end(l: list):
    i = len(l) - 1
    # If you're not sure the items of l are strings, then, you can do while l[i] == ""
    while not l[i] and i > 0:
        i -= 1

    return l[:i + 1]
```

It's simple and avoids creating countless copies of l

Body:
i have some list of strings. I want to remove empty strings from the end of the list (i.e.  each list should end with a non empty element).

input
list1= ['a1','b1','c1','d1','']
list2 = ['a2','','b2','','c2','d2','']
list3 = ['a3','','b3','','','']
list4 = ['','','','','']

output

list1= ['a1','b1','c1','d1']
list2 = ['a2','','b2','','c2','d2']
list3 = ['a3','','b3']
list4 = ['']

if all the elements are empty strings , only one empty string should remain (eg. list4).

Body:
The easiest way (in my opinion)

def remove_empty_at_end(l: list):
    i = len(l) - 1
    # If you're not sure the items of l are strings, then, you can do while l[i] == ""
    while not l[i] and i > 0:
        i -= 1

    return l[:i + 1]

It's simple and avoids creating countless copies of l


问:
Is there a way how to navigate to destination and add another to backtstack in NavigationManager?
Hi I am new to android NavigationManager.

Consider fragments A, B and C conected in nav_graph as shown in the picture.

Basically what I am trying to achieve is to navigate from fragment A directly to C. But when clicking on back button, I want it to behave as if I were first in fragment B.

So A->C,   on back buttons: C->B->A

Is there some way, how I could add fragment B to backstack without actually showing it using NavigationManager?

答:
So it seems I should be more careful when reading documentation. I missed this site.

There is mechanism for custom back behavior. All I needed to do was to add this code to fragment C class:

```<code>//use onResume if you want to handle orientation change
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    val callback = requireActivity().onBackPressedDispatcher.addCallback(this, object :
        OnBackPressedCallback(true) {
        override fun handleOnBackPressed() {
            val options = NavOptions.Builder()
                .setPopUpTo(R.id.fragmentC, true)
                .build()

            navController.navigate(R.id.fragmentB, options)
        }
    })
}
</code>```

My mindset was wrong the whole time. I was trying to add B to backstack when launching C. What I had to do instead in fragment C on back button pressed was going forward to B and delete C from backstack.

Body:
So it seems I should be more careful when reading documentation. I missed this site.

There is mechanism for custom back behavior. All I needed to do was to add this code to fragment C class:

//use onResume if you want to handle orientation change
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    val callback = requireActivity().onBackPressedDispatcher.addCallback(this, object :
        OnBackPressedCallback(true) {
        override fun handleOnBackPressed() {
            val options = NavOptions.Builder()
                .setPopUpTo(R.id.fragmentC, true)
                .build()

            navController.navigate(R.id.fragmentB, options)
        }
    })
}

My mindset was wrong the whole time. I was trying to add B to backstack when launching C. What I had to do instead in fragment C on back button pressed was going forward to B and delete C from backstack.


问:
IllegalArgument Exception : Unable to compile
I am getting IlleagalArgument Exception while retreiving Xpath for a particular node

I need to retrieve the below webpage link which follows the title WebPages ,I  tried using the below expression but it is not able compile (Please see the comment section for the html )

```<code>page.getNode("//h3[. = 'Webpages:']/following-sibling::/ul[@class='list-entity-locations']/li/a/text()")
</code>```

This is what I tried but got Exception

java.lang.IllegalArgumentException: Unable to compile

答: The right syntax is following-sibling::ul, not following-sibling::/ul.

Body:
I am getting IlleagalArgument Exception while retreiving Xpath for a particular node

I need to retrieve the below webpage link which follows the title WebPages ,I  tried using the below expression but it is not able compile (Please see the comment section for the html )

page.getNode("//h3[. = 'Webpages:']/following-sibling::/ul[@class='list-entity-locations']/li/a/text()")

This is what I tried but got Exception

java.lang.IllegalArgumentException: Unable to compile


问:
Unity3D doen't see kazakh language letters
I'm new developer in Unity3D. When I write kazak language letter like ҚӨӘІҢ Unity shows ????? What I need to do? If I get data from json it will be shown correctly.</p>

答: You need to add a custom font and use that as the default font probably doesn't support those characters.</p>


问:
Automatically enter SSH password with script
I need to create a script that automatically inputs a password to OpenSSH ssh client.

Let's say I need to SSH into myname@somehost with the password a1234b.

I've already tried...

```<code>#~/bin/myssh.sh
ssh myname@somehost
a1234b
</code>```

...but this does not work.

How can I get this functionality into a script?

答:
This is how I login to my servers:

```<code>ssp <server_ip>
</code>```

alias ssp='/home/myuser/Documents/ssh_script.sh'

cat /home/myuser/Documents/ssh_script.sh

ssp:

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

sshpass -p mypassword ssh root@$1
</code>```

And therefore:

```<code>ssp server_ip
</code>```

Body:
I need to create a script that automatically inputs a password to OpenSSH ssh client.

Let's say I need to SSH into myname@somehost with the password a1234b.

I've already tried...

#~/bin/myssh.sh
ssh myname@somehost
a1234b

...but this does not work.

How can I get this functionality into a script?

Body:
This is how I login to my servers:

ssp <server_ip>

alias ssp='/home/myuser/Documents/ssh_script.sh'

cat /home/myuser/Documents/ssh_script.sh

ssp:

#!/bin/bash

sshpass -p mypassword ssh root@$1

And therefore:

ssp server_ip


问:
How to get abstract user first_name and last_name and how to update it
```<code># models.py

class User(AbstractUser):
   `` id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

class Employee(models.Model):
    employee = models.OneToOneField(User, on_delete=models.CASCADE)
     reporting_manager = models.ForeignKey('self', on_delete=models.CASCADE, related_name='reporting_managers',
                                          null=True, blank=True)
    date_of_birth = models.DateField(null=True, blank=True)
    date_of_join = models.DateField(null=True, blank=True)
    date_of_exit = models.DateField(null=True, blank=True)
</code>```

I want here first_name and last_name from Abstract user and that should be also updatable. Help me out this issue.

```<code># views.py

class EmployeeUpdateView(UpdateView):

"""
For updating profile of each employee :update view
"""

model = Employee

fields = ('reporting_manager','date_of_birth','date_of_join','gender','address','photo',\
          'department','employee_code','blood_group','designation','phone_no','personal_email_id','official_email_id',\
          'email_domain','city','allowed_apps')

template_name = "registration/update_employee.html"
</code>```

答:
```<code>views.py i added this
def post(self, request, **kwargs):

    """
    This function here for updating first_name and last_name by getting details from update_employee form \
    and explicitly we are adding first_name and last_name by using reference of particular names from form

    """
    data = request.POST.dict()
    print("Data coming from update of employee data ", data)
    emp_code = data['employee_code']
    employee = Employee.objects.get(employee_code=emp_code)
    emp_user = employee.employee
    emp_user.first_name = data['first_name']
    emp_user.last_name = data['last_name']
    emp_user.save()
</code>```

Body:
# models.py

class User(AbstractUser):
   `` id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

class Employee(models.Model):
    employee = models.OneToOneField(User, on_delete=models.CASCADE)
     reporting_manager = models.ForeignKey('self', on_delete=models.CASCADE, related_name='reporting_managers',
                                          null=True, blank=True)
    date_of_birth = models.DateField(null=True, blank=True)
    date_of_join = models.DateField(null=True, blank=True)
    date_of_exit = models.DateField(null=True, blank=True)

I want here first_name and last_name from Abstract user and that should be also updatable. Help me out this issue.

# views.py

class EmployeeUpdateView(UpdateView):

"""
For updating profile of each employee :update view
"""

model = Employee

fields = ('reporting_manager','date_of_birth','date_of_join','gender','address','photo',\
          'department','employee_code','blood_group','designation','phone_no','personal_email_id','official_email_id',\
          'email_domain','city','allowed_apps')

template_name = "registration/update_employee.html"


答:
You have forgotten curly braces. Also, you can create the url string before and use it:</p>

```<code> const url = "https://www.countryflags.io/"+this.state.countryCode+"/shiny/64.png";
 <img src={url}/>
</code>```

Title: Source of Img should be dynamic

Body:
how can i load an img src dynamic with React ?
I tried the following:

 const country = this.state.countryCode;

But i got the error:

Parsing error: Unexpected token

Body:
You have forgotten curly braces. Also, you can create the url string before and use it:

 const url = "https://www.countryflags.io/"+this.state.countryCode+"/shiny/64.png";
 <img src={url}/>


问:
How to pass an array of primitives as varargs?
I'm stuck trying to pass an array of primitives (in my case an int[]) to a method with varargs.

Let's say:

```<code>    // prints: 1 2
    System.out.println(String.format("%s %s", new String[] { "1", "2"}));
    // fails with java.util.MissingFormatArgumentException: Format specifier '%s'
    System.out.println(String.format("%s %s", new int[] { 1, 2 }));
</code>```

Note however that the first line gets the following warning:

Type String[] of the last argument to method format(String, Object...) doesn't exactly match the vararg parameter type. Cast to Object[] to confirm the non-varargs invocation, or pass individual arguments of type Object for a varargs invocation.

Note also I don't input the array with a constructor, but I get it from the enclosing method, whose signature I can't change, like:

```<code>private String myFormat(int[] ints) {
    // whatever format it is, it's just an example, assuming the number of ints
    // is greater than the number of the format specifiers
    return String.format("%s %s %s %s", ints);
}
</code>```

答:
int varargs to object varargs, creating a formater with blank separator</p>

```<code> private void method( int ... values) {
        String.format(StringUtils.repeat("%d", " ", values.length),  Arrays.stream( values ).boxed().toArray());
 }
</code>```

Body:
I'm stuck trying to pass an array of primitives (in my case an int[]) to a method with varargs.

Let's say:

    // prints: 1 2
    System.out.println(String.format("%s %s", new String[] { "1", "2"}));
    // fails with java.util.MissingFormatArgumentException: Format specifier '%s'
    System.out.println(String.format("%s %s", new int[] { 1, 2 }));

Note however that the first line gets the following warning:

Type String[] of the last argument to method format(String, Object...) doesn't exactly match the vararg parameter type. Cast to Object[] to confirm the non-varargs invocation, or pass individual arguments of type Object for a varargs invocation.

Note also I don't input the array with a constructor, but I get it from the enclosing method, whose signature I can't change, like:

private String myFormat(int[] ints) {
    // whatever format it is, it's just an example, assuming the number of ints
    // is greater than the number of the format specifiers
    return String.format("%s %s %s %s", ints);
}

Body:
int varargs to object varargs, creating a formater with blank separator

 private void method( int ... values) {
        String.format(StringUtils.repeat("%d", " ", values.length),  Arrays.stream( values ).boxed().toArray());
 }


答:
```<code>def trim_empty_strings(l):
    while len(l) > 1 and l[-1] == '':
        l = l[:-1]
    return l

trim_empty_strings(['a','b','', '']
trim_empty_strings(['','',''])
</code>```

Title: How to remove empty strings from the end of a list of strings (only at the end)


问:
DialogFragment focus EditText on dialog open for API 28
I want to focus the first TextInputEditText in layout and automatically  display the soft keyboard when dialog is shown

I'm targeting API level 28.

Layout:

```<code>        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/d_add_edit_name_til"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="@dimen/activity_vertical_margin"
            android:layout_marginTop="@dimen/activity_vertical_margin"
            android:layout_marginEnd="@dimen/activity_vertical_margin"
            android:theme="@style/TextInputLayoutAppearance"
            >
            <com.google.android.material.textfield.TextInputEditText
                android:id="@+id/d_add_edit_name_et"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="User email"
                android:imeOptions="actionDone"
                android:inputType="textCapSentences"
                android:singleLine="true"
                android:focusableInTouchMode="true"
                android:focusable="true"
            >
                <requestFocus />
            </com.google.android.material.textfield.TextInputEditText>
        </com.google.android.material.textfield.TextInputLayout>
</code>```

DialogFragment code:

```<code>@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
    final Dialog dialog = super.onCreateDialog(savedInstanceState);
    dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
    dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    return dialog;
}

....

@Override
public void onResume(){
    super.onResume();

    int dialogWidth = Functions.convertDpToPixel(300,activity);
    int dialogHeight = Functions.convertDpToPixel(250,activity);

    new Handler().post(() -> {
        getDialog().getWindow().setLayout(dialogWidth, dialogHeight);
    });
}
</code>```

The answers from this thread helped me solve the issue for API < 28.

I know from Android 9 changes documentation that:

Additionally, activities no longer implicitly assign initial focus in touch-mode. Instead, it is up to you to explicitly request initial focus, if desired.

One of the ways to explicitly request initial focus (as discussed here) is by adding <requestFocus /> tag inside EditText, but still no success for API level 28 + DialogFragment

*Note that DialogFragment is from andoridx library (androidx.fragment.app.DialogFragment)

Anyone else having this issue?

Edit:
The only way I managed to make this work is by adding the following code to onViewCreated:

```<code>    new Handler().postDelayed(() -> {
        nameEt.requestFocus();
        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(nameEt, InputMethodManager.SHOW_IMPLICIT);
    },200);
</code>```

I don't consider this to be a valid answer as using threads in this manner makes the code unpredictable. Still waiting for a good answer

答:
```<code>TextInputEditText textInputEditText= (TextInputEditText) findViewById(R.id.d_add_edit_name_et);
textInputEditText.requestFocus();
</code>```

Body:
I want to focus the first TextInputEditText in layout and automatically  display the soft keyboard when dialog is shown

I'm targeting API level 28.

Layout:

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/d_add_edit_name_til"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="@dimen/activity_vertical_margin"
            android:layout_marginTop="@dimen/activity_vertical_margin"
            android:layout_marginEnd="@dimen/activity_vertical_margin"
            android:theme="@style/TextInputLayoutAppearance"
            >
            <com.google.android.material.textfield.TextInputEditText
                android:id="@+id/d_add_edit_name_et"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="User email"
                android:imeOptions="actionDone"
                android:inputType="textCapSentences"
                android:singleLine="true"
                android:focusableInTouchMode="true"
                android:focusable="true"
            >
                <requestFocus />
            </com.google.android.material.textfield.TextInputEditText>
        </com.google.android.material.textfield.TextInputLayout>

DialogFragment code:

@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
    final Dialog dialog = super.onCreateDialog(savedInstanceState);
    dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
    dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    return dialog;
}

....

@Override
public void onResume(){
    super.onResume();

    int dialogWidth = Functions.convertDpToPixel(300,activity);
    int dialogHeight = Functions.convertDpToPixel(250,activity);

    new Handler().post(() -> {
        getDialog().getWindow().setLayout(dialogWidth, dialogHeight);
    });
}

The answers from this thread helped me solve the issue for API < 28.

I know from Android 9 changes documentation that:

Additionally, activities no longer implicitly assign initial focus in touch-mode. Instead, it is up to you to explicitly request initial focus, if desired.

One of the ways to explicitly request initial focus (as discussed here) is by adding <requestFocus /> tag inside EditText, but still no success for API level 28 + DialogFragment

*Note that DialogFragment is from andoridx library (androidx.fragment.app.DialogFragment)

Anyone else having this issue?

Edit:
The only way I managed to make this work is by adding the following code to onViewCreated:

    new Handler().postDelayed(() -> {
        nameEt.requestFocus();
        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(nameEt, InputMethodManager.SHOW_IMPLICIT);
    },200);

I don't consider this to be a valid answer as using threads in this manner makes the code unpredictable. Still waiting for a good answer