问:
Receiving Firebase Notifications in Foreground but not Background
I've tried everything to get the alerts to pop up while in the background. I receive the data when app is open or while launching. Because I receive the notifications I'm assuming it's in my AppDelegate code or perhaps something wrong in my .plist??? I've followed a few of the standard tutorials on firebase notifications, all this code is from those tutorials.</p>

```<code>import UIKit
import CoreData
import Firebase
import UserNotifications
import FirebaseInstanceID
import FirebaseMessaging

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {
    var window: UIWindow?
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        FirebaseApp.configure()
        if #available(iOS 10.0, *) {
            // For iOS 10 display notification (sent via APNS)
            UNUserNotificationCenter.current().delegate = self
            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
            UNUserNotificationCenter.current().requestAuthorization(
                options: authOptions,
                completionHandler: {_, _ in })
            // For iOS 10 data message (sent via FCM
            Messaging.messaging().delegate = self
        } else {
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }

        application.registerForRemoteNotifications()

        // Override point for customization after application launch.

        NotificationCenter.default.addObserver(self, selector: #selector(self.tokenRefreshNotification(_:)),
                                                         name: NSNotification.Name.InstanceIDTokenRefresh, object: nil)

        return true
    }

    func application(application: UIApplication,
                     didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        Messaging.messaging().apnsToken = deviceToken
    }

    func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
        print("refreshed token")
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

      //  Messaging.messaging().disconnect()
       // print("Disconnected from FCM.")
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
        connectToFcm()
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        // Saves changes in the application's managed object context before the application terminates.
        self.saveContext()
    }

    // MARK: - Core Data stack

    lazy var persistentContainer: NSPersistentContainer = {
        /*
         The persistent container for the application. This implementation
         creates and returns a container, having loaded the store for the
         application to it. This property is optional since there are legitimate
         error conditions that could cause the creation of the store to fail.
        */
        let container = NSPersistentContainer(name: "firetail")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

    // MARK: - Core Data Saving support

    func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }
    @objc private func tokenRefreshNotification(_ notification: Notification) {
        if let refreshedToken = InstanceID.instanceID().token() {
            print("InstanceID token: \(refreshedToken)")
        }

        // Connect to FCM since connection may have failed when attempted before having a token.
        connectToFcm()
    }

    func connectToFcm() {
        // Won't connect since there is no token
        guard InstanceID.instanceID().token() != nil else {
            return
        }

        // Disconnect previous FCM connection if it exists.
        Messaging.messaging().disconnect()

        Messaging.messaging().connect { (error) in
            if error != nil {
                print("Unable to connect with FCM. \(error?.localizedDescription ?? "")")
            } else {
                print("Connected to FCM.")
            }
        }
    }

    public func application(received remoteMessage: MessagingRemoteMessage) {

        print(remoteMessage.appData)
    }

}
</code>```

答:
A few things to note:

The simulator cannot receive push notifications.

You must have push notifications and background modes (remote notifications & background fetch) enabled in your project's capabilities.

Try adding these lines of code to your app delegate:

```<code>func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
        // Will not be called until you open your application from the remote notification (returns to foreground)

        // Note: *with swizzling disabled you must let Messaging know about the message
        // Messaging.messaging().appDidReceiveMessage(userInfo)`

        // Print message ID.
        if let messageId = userInfo["gcm.message_id"] {
            print("Message Id: \(messageId)")
        }

        // Print full message.
        print(userInfo)
        Messaging.messaging().appDidReceiveMessage(userInfo)
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        // Will not be called until you open your application from the remote notification (returns to foreground)

        // Note: *with swizzling disabled you must let Messaging know about the message
        // Messaging.messaging().appDidReceiveMessage(userInfo)

        // Print message id
        if let messageId = userInfo["gcm.message_id"] {
            print("Message Id: \(messageId)")
        }

        // Print full message.
        print(userInfo)
        Messaging.messaging().appDidReceiveMessage(userInfo)

        completionHandler(UIBackgroundFetchResult.newData)
    }
</code>```

I also noticed you map your APNS token to Messaging (in didRegisterForRemoteNotificationsWithDeviceToken) using :

```<code>Messaging.messaging().apnsToken = deviceToken
</code>```

I would try your luck replacing it with the following:

```<code>Messaging.messaging().setAPNSToken(deviceToken, type: MessagingAPNSTokenType.sandbox)
        Messaging.messaging().setAPNSToken(deviceToken, type: MessagingAPNSTokenType.prod)
</code>```

Good luck!

Body:
I've tried everything to get the alerts to pop up while in the background. I receive the data when app is open or while launching. Because I receive the notifications I'm assuming it's in my AppDelegate code or perhaps something wrong in my .plist??? I've followed a few of the standard tutorials on firebase notifications, all this code is from those tutorials.

import UIKit
import CoreData
import Firebase
import UserNotifications
import FirebaseInstanceID
import FirebaseMessaging

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {
    var window: UIWindow?
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        FirebaseApp.configure()
        if #available(iOS 10.0, *) {
            // For iOS 10 display notification (sent via APNS)
            UNUserNotificationCenter.current().delegate = self
            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
            UNUserNotificationCenter.current().requestAuthorization(
                options: authOptions,
                completionHandler: {_, _ in })
            // For iOS 10 data message (sent via FCM
            Messaging.messaging().delegate = self
        } else {
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }

        application.registerForRemoteNotifications()

        // Override point for customization after application launch.

        NotificationCenter.default.addObserver(self, selector: #selector(self.tokenRefreshNotification(_:)),
                                                         name: NSNotification.Name.InstanceIDTokenRefresh, object: nil)

        return true
    }

    func application(application: UIApplication,
                     didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        Messaging.messaging().apnsToken = deviceToken
    }

    func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
        print("refreshed token")
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

      //  Messaging.messaging().disconnect()
       // print("Disconnected from FCM.")
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
        connectToFcm()
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        // Saves changes in the application's managed object context before the application terminates.
        self.saveContext()
    }

    // MARK: - Core Data stack

    lazy var persistentContainer: NSPersistentContainer = {
        /*
         The persistent container for the application. This implementation
         creates and returns a container, having loaded the store for the
         application to it. This property is optional since there are legitimate
         error conditions that could cause the creation of the store to fail.
        */
        let container = NSPersistentContainer(name: "firetail")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

    // MARK: - Core Data Saving support

    func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }
    @objc private func tokenRefreshNotification(_ notification: Notification) {
        if let refreshedToken = InstanceID.instanceID().token() {
            print("InstanceID token: \(refreshedToken)")
        }

        // Connect to FCM since connection may have failed when attempted before having a token.
        connectToFcm()
    }

    func connectToFcm() {
        // Won't connect since there is no token
        guard InstanceID.instanceID().token() != nil else {
            return
        }

        // Disconnect previous FCM connection if it exists.
        Messaging.messaging().disconnect()

        Messaging.messaging().connect { (error) in
            if error != nil {
                print("Unable to connect with FCM. \(error?.localizedDescription ?? "")")
            } else {
                print("Connected to FCM.")
            }
        }
    }

    public func application(received remoteMessage: MessagingRemoteMessage) {

        print(remoteMessage.appData)
    }

}

Body:
A few things to note:

The simulator cannot receive push notifications.

You must have push notifications and background modes (remote notifications & background fetch) enabled in your project's capabilities.

Try adding these lines of code to your app delegate:

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
        // Will not be called until you open your application from the remote notification (returns to foreground)

        // Note: *with swizzling disabled you must let Messaging know about the message
        // Messaging.messaging().appDidReceiveMessage(userInfo)`

        // Print message ID.
        if let messageId = userInfo["gcm.message_id"] {
            print("Message Id: \(messageId)")
        }

        // Print full message.
        print(userInfo)
        Messaging.messaging().appDidReceiveMessage(userInfo)
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        // Will not be called until you open your application from the remote notification (returns to foreground)

        // Note: *with swizzling disabled you must let Messaging know about the message
        // Messaging.messaging().appDidReceiveMessage(userInfo)

        // Print message id
        if let messageId = userInfo["gcm.message_id"] {
            print("Message Id: \(messageId)")
        }

        // Print full message.
        print(userInfo)
        Messaging.messaging().appDidReceiveMessage(userInfo)

        completionHandler(UIBackgroundFetchResult.newData)
    }

I also noticed you map your APNS token to Messaging (in didRegisterForRemoteNotificationsWithDeviceToken) using :

Messaging.messaging().apnsToken = deviceToken

I would try your luck replacing it with the following:

Messaging.messaging().setAPNSToken(deviceToken, type: MessagingAPNSTokenType.sandbox)
        Messaging.messaging().setAPNSToken(deviceToken, type: MessagingAPNSTokenType.prod)

Good luck!


来源: stackexchange

问:
Accept user variable and create a template.py using python[2,7][redhat 6.7]
Scenario : I have a test.py file which has the following code.

```<code>import json
import os
import sys
def check()
    url = os.popen("curl api.openweathermap.org/data/2.5/weather?id=2172797 2>dev/null")
    uri = json.loads(url)
    f_check = file("/home/1/file1.txt",'r')
    f_data = f_check.read()
    chk_data = int(f_data)
    f1 = open("file1.txt", "w")
    n1 = f1.write(str(uri) + "\n")
    f1.close()
</code>```

In the above mentioned test.py file is in location " /home/check " I want to use this as a template file which can be used to deploy for other uses in different location say "/home/word" just Changing some variables in it like url and file1.txt file location which user will provide.
I couldn't find a convenient way to do that.

Any help will be appreciated.

答:
Question: ...  Changing some variables in it like url and file1.txt file location

It's unclear what you want to do with chk_data.
Tried your example code and found you are reading chk_data but doing nothing with it afterwards. Please edit your Question and explain this more detailed with example data.

This example can be used with different url, file lcationand filename.

Note: I use module urllib instead of os.popen("curl....

First Solution, passing Parameters from Terminal Window:

```<code>import urllib.request
import urllib.parse

def check(url, params, filename):
    params = urllib.parse.urlencode(params)
    url = "{}?{}".format(url, params)

    with urllib.request.urlopen(url) as f:
        json_response = json.loads(f.read().decode('utf-8'))

    with open(filename, 'w') as f_out:
        f_out.write(str(json_response))

if __name__ == '__main__':
    url = sys.argv[1]
    params = {}
    for param in sys.argv[2].split(' '):
        key, value = param.split('=')
        params[key] = value

    if url == 'openweathermap.org':
        url = 'http://samples.openweathermap.org/data/2.5/weather'
        params['appid'] = 'b1b15e88fa797225412429c1c50c122a1'

    check(url, params, sys.argv[3])
</code>```

Usage:

```<code>:#  python openweathermap.org "id=2172797" /home/word/my_file.txt
</code>```

Second Solution, using test.py as a Python module with import check.

Parameters inside a new Python Script.

Note: This requires home.check.test is in your PYTHONPATH!

Create a new *.py file, e.g openweathermap.py

```<code>from home.check.test import check

if __name__ == '__main__':
    url = 'http://samples.openweathermap.org/data/2.5/weather'
    params = {'id':'2172797', 'appid':'b1b15e88fa797225412429c1c50c122a1'}
    check(url, params, '/home/word/my_file.txt')
</code>```

Usage:

```<code>:#  python /home/check/openweathermap.py
</code>```

Tested with Python: 3.4.2

ContentLicense: CC BY-SA 3.0

Body:
Scenario : I have a test.py file which has the following code.

import json
import os
import sys
def check()
    url = os.popen("curl api.openweathermap.org/data/2.5/weather?id=2172797 2>dev/null")
    uri = json.loads(url)
    f_check = file("/home/1/file1.txt",'r')
    f_data = f_check.read()
    chk_data = int(f_data)
    f1 = open("file1.txt", "w")
    n1 = f1.write(str(uri) + "\n")
    f1.close()

In the above mentioned test.py file is in location " /home/check " I want to use this as a template file which can be used to deploy for other uses in different location say "/home/word" just Changing some variables in it like url and file1.txt file location which user will provide.
I couldn't find a convenient way to do that.

Any help will be appreciated.

Body:
Question: ...  Changing some variables in it like url and file1.txt file location

It's unclear what you want to do with chk_data.
Tried your example code and found you are reading chk_data but doing nothing with it afterwards. Please edit your Question and explain this more detailed with example data.

This example can be used with different url, file lcationand filename.

Note: I use module urllib instead of os.popen("curl....

First Solution, passing Parameters from Terminal Window:

import urllib.request
import urllib.parse

def check(url, params, filename):
    params = urllib.parse.urlencode(params)
    url = "{}?{}".format(url, params)

    with urllib.request.urlopen(url) as f:
        json_response = json.loads(f.read().decode('utf-8'))

    with open(filename, 'w') as f_out:
        f_out.write(str(json_response))

if __name__ == '__main__':
    url = sys.argv[1]
    params = {}
    for param in sys.argv[2].split(' '):
        key, value = param.split('=')
        params[key] = value

    if url == 'openweathermap.org':
        url = 'http://samples.openweathermap.org/data/2.5/weather'
        params['appid'] = 'b1b15e88fa797225412429c1c50c122a1'

    check(url, params, sys.argv[3])

Usage:

:#  python openweathermap.org "id=2172797" /home/word/my_file.txt

Second Solution, using test.py as a Python module with import check.

Parameters inside a new Python Script.

Note: This requires home.check.test is in your PYTHONPATH!

Create a new *.py file, e.g openweathermap.py

from home.check.test import check

if __name__ == '__main__':
    url = 'http://samples.openweathermap.org/data/2.5/weather'
    params = {'id':'2172797', 'appid':'b1b15e88fa797225412429c1c50c122a1'}
    check(url, params, '/home/word/my_file.txt')

Usage:

:#  python /home/check/openweathermap.py

Tested with Python: 3.4.2


问:
A state mutation was detected between dispatches but I haven't mutated state
I know this question has been asked before, but in almost all of them talk about the OP mutating the state directly, which I've tried to avoid using techniques like the spread operator (in both objects and arrays) but in spite of that I'm getting the following error:

```<code>Uncaught Error: A state mutation was detected between dispatches, in the path `courses.0`. This may cause incorrect behavior. (http://redux.js.org/docs/Troubleshooting.html#never-mutate-reducer-arguments)
  at invariant (eval at <anonymous> (bundle.js:922), <anonymous>:40:15)
  at eval (eval at <anonymous> (bundle.js:3825), <anonymous>:50:36)
  at eval (eval at <anonymous> (bundle.js:3846), <anonymous>:14:16)
  at dispatch (eval at <anonymous> (bundle.js:3853), <anonymous>:37:18)
  at eval (eval at <anonymous> (bundle.js:1151), <anonymous>:63:5)
  at eval (eval at <anonymous> (bundle.js:3846), <anonymous>:11:18)
  at Object.eval [as saveCourse] (eval at <anonymous> (bundle.js:3860), <anonymous>:4:12)
  at Object.ManageCoursePage._this.saveCourse [as onSave] (eval at <anonymous> (bundle.js:2080), <anonymous>:134:27)
  at CourseForm._this.onHandleSave (eval at <anonymous> (bundle.js:2052), <anonymous>:93:19)
  at Object.ReactErrorUtils.invokeGuardedCallback (eval at <anonymous> (bundle.js:1301), <anonymous>:69:16)
</code>```

I read the article that the error points to, and as it suggests I checked if I was manually mutating the state in my reducer and I can't see where that could be happening:

```<code>const courseReducer = (state = initialState.courses, action) => {
  switch (action.type) {
    case types.LOAD_COURSE_SUCCESS:
      return action.courses;
    case types.CREATE_COURSE_SUCCESS:
    //This action throw the error
      debugger;
      return [
        ...state,
        Object.assign({}, action.course)
      ];
    case types.UPDATE_COURSE_SUCCESS:
     //This action throw the error
      debugger;
      return [
        ...state.filter(course => course.id !== action.course.id),
        Object.assign({}, action.course)
      ];
    case types.DELETE_COURSE_SUCCESS:
      return [...state.filter(course => course.id !== action.courseId)];
    default:
      return state;
  }
};
</code>```

Here's a sandbox with part of the application that can be used to replicate the error, which weirdly only happens from times to times when I create a new course or try to edit an existing one (actions CREATE_COURSE_SUCCESS and UPDATE_COURSE_SUCCESSrespectively in my courseReducer)

I'd really appreciate if anyone could help me figure out where could be lying the source of this error.

答:
The problem is that you are mutating state, inside CoursesPage.js, in mapStateToProps:

```<code>let courses = state.courses.sort((c1, c2) =>
  c1.title.localeCompare(c2.title, 'en', { sensitivity: 'base' }),
);
</code>```

Array#sort is an in place operation, so it mutates the source array by sorting the source array in place. That means, sort is mutating state.courses, thus causing the error. Instead, make a copy of state.courses before you sort it:

```<code>[...state.courses]
</code>```

The above uses spread syntax to spread the elements into a new array essentially cloning it. This is the same as Array#slice. Then you can sort it like so:

```<code>let courses = [...state.courses].sort((c1, c2) =>
  c1.title.localeCompare(c2.title, 'en', { sensitivity: 'base' }),
);
</code>```

This will not mutate the original state.courses and will not throw an error.

Note: There are also some places where you are mutating this.state directly, such as in line 32 of ManageCoursePage.js where you do:

```<code>this.state.errors = {}
</code>```

Only ever mutate the this.state object in the constructor of the component. Use setState instead.

Body:
I know this question has been asked before, but in almost all of them talk about the OP mutating the state directly, which I've tried to avoid using techniques like the spread operator (in both objects and arrays) but in spite of that I'm getting the following error:

Uncaught Error: A state mutation was detected between dispatches, in the path `courses.0`. This may cause incorrect behavior. (http://redux.js.org/docs/Troubleshooting.html#never-mutate-reducer-arguments)
  at invariant (eval at <anonymous> (bundle.js:922), <anonymous>:40:15)
  at eval (eval at <anonymous> (bundle.js:3825), <anonymous>:50:36)
  at eval (eval at <anonymous> (bundle.js:3846), <anonymous>:14:16)
  at dispatch (eval at <anonymous> (bundle.js:3853), <anonymous>:37:18)
  at eval (eval at <anonymous> (bundle.js:1151), <anonymous>:63:5)
  at eval (eval at <anonymous> (bundle.js:3846), <anonymous>:11:18)
  at Object.eval [as saveCourse] (eval at <anonymous> (bundle.js:3860), <anonymous>:4:12)
  at Object.ManageCoursePage._this.saveCourse [as onSave] (eval at <anonymous> (bundle.js:2080), <anonymous>:134:27)
  at CourseForm._this.onHandleSave (eval at <anonymous> (bundle.js:2052), <anonymous>:93:19)
  at Object.ReactErrorUtils.invokeGuardedCallback (eval at <anonymous> (bundle.js:1301), <anonymous>:69:16)

I read the article that the error points to, and as it suggests I checked if I was manually mutating the state in my reducer and I can't see where that could be happening:

const courseReducer = (state = initialState.courses, action) => {
  switch (action.type) {
    case types.LOAD_COURSE_SUCCESS:
      return action.courses;
    case types.CREATE_COURSE_SUCCESS:
    //This action throw the error
      debugger;
      return [
        ...state,
        Object.assign({}, action.course)
      ];
    case types.UPDATE_COURSE_SUCCESS:
     //This action throw the error
      debugger;
      return [
        ...state.filter(course => course.id !== action.course.id),
        Object.assign({}, action.course)
      ];
    case types.DELETE_COURSE_SUCCESS:
      return [...state.filter(course => course.id !== action.courseId)];
    default:
      return state;
  }
};

Here's a sandbox with part of the application that can be used to replicate the error, which weirdly only happens from times to times when I create a new course or try to edit an existing one (actions CREATE_COURSE_SUCCESS and UPDATE_COURSE_SUCCESSrespectively in my courseReducer)

I'd really appreciate if anyone could help me figure out where could be lying the source of this error.

Body:
The problem is that you are mutating state, inside CoursesPage.js, in mapStateToProps:

let courses = state.courses.sort((c1, c2) =>
  c1.title.localeCompare(c2.title, 'en', { sensitivity: 'base' }),
);

Array#sort is an in place operation, so it mutates the source array by sorting the source array in place. That means, sort is mutating state.courses, thus causing the error. Instead, make a copy of state.courses before you sort it:

[...state.courses]

The above uses spread syntax to spread the elements into a new array essentially cloning it. This is the same as Array#slice. Then you can sort it like so:

let courses = [...state.courses].sort((c1, c2) =>
  c1.title.localeCompare(c2.title, 'en', { sensitivity: 'base' }),
);

This will not mutate the original state.courses and will not throw an error.

Note: There are also some places where you are mutating this.state directly, such as in line 32 of ManageCoursePage.js where you do:

this.state.errors = {}

Only ever mutate the this.state object in the constructor of the component. Use setState instead.


问:
Go equivalent of C's negated scansets
What is the way to mimick the negated scansets that exist in C?

For an example input string: aaaa, bbbb

In go using:

```<code>fmt.Sscanf(input, "%s, %s", &str1, &str2)
</code>```

The result is only str1 being set as: aaaa,

In C one could use a format string as "%[^,], %s" to avoid this problem, is there a way to accomplish this in go?

答:
You could always go for regular expressions;</p>

```<code>re := regexp.MustCompile(`(\w+), (\w+)`)
input := "aaaa, bbbb"
fmt.Printf("%#v\n", re.FindStringSubmatch(input))
// Prints []string{"aaaa, bbbb", "aaaa", "bbbb"}
</code>```

Title: Go equivalent of C's negated scansets

Body:
What is the way to mimick the negated scansets that exist in C?

For an example input string: aaaa, bbbb

In go using:

fmt.Sscanf(input, "%s, %s", &str1, &str2)

The result is only str1 being set as: aaaa,

In C one could use a format string as "%[^,], %s" to avoid this problem, is there a way to accomplish this in go?

Body:
You could always go for regular expressions;

re := regexp.MustCompile(`(\w+), (\w+)`)
input := "aaaa, bbbb"
fmt.Printf("%#v\n", re.FindStringSubmatch(input))
// Prints []string{"aaaa, bbbb", "aaaa", "bbbb"}


问:
how to count lines in javafx text area
If text wrapping was set to off, then this would be a trivial matter of course, because lines can be easily counted by counting the number of newline characters. Unfortunately, when text wrapping is on, there does not seem to be any obvious and non-messy way to do this, other than actually putting in newline characters at the end of every row when initializing the box.

Up until now, this is how I solved the problem, however it is highly undesirable since, in many cases, it inserts a newline into the middle of a word, and of course, this solution is convoluted and messy. Does anyone have any suggestions? If I were to wrap my text area inside a textflow container, would there be a way to get around this?

答:
From your TextArea

TextArea textArea = new TextArea();

Take the text

String toCount = textArea.getText();

Split it into lines

String[] lineArray = toCount.split("\n");

Index 0 to lineArray.length -1 is your lines - where lineArray.length -1 is your total.

How to split a string in Java

How you insert the line count number if you want them to be visable is another matter.

Title: how to count lines in javafx text area


问:
My css and javascript files not running
I installed Nginx server for my laravel project. But css and javascript file not working. Css and javascript file downloadable on server. For example http://myipaddress/css/bootstrap.css download the bootstrap.css file. I call the css file like <link href="{{ URL::asset('css/bootstrap.css') }}" rel="stylesheet"> like this.

My source code

My public folder permissions

/etc/nginx/sites-available/default looks like the following

```<code># Default server configuration
#
server {
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;

# SSL configuration
#
 listen 443 ssl default_server;
 listen [::]:443 ssl default_server;
#
# Note: You should disable gzip for SSL traffic.
# See: https://bugs.debian.org/773332
#
# Read up on ssl_ciphers to ensure a secure configuration.
# See: https://bugs.debian.org/765782
#
# Self signed certs generated by the ssl-cert package
# Don't use them in a production server!
#
# include snippets/snakeoil.conf;

root /var/www/english4-u.com/public;

# Add index.php to the list if you are using PHP
index index.php index.html index.htm;

server_name english4-u.com;
ssl_certificate /etc/nginx/ssl/nginx.crt;
ssl_certificate_key /etc/nginx/ssl/nginx.key;

location / {
    # First attempt to serve request as file, then
    # as directory, then fall back to displaying a 404.
    try_files $uri $uri/ /index.php?$query_string;
}

# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
location ~ \.php$ {
#   include snippets/fastcgi-php.conf;
#
#   # With php7.0-cgi alone:
#   fastcgi_pass 127.0.0.1:9000;
#   # With php7.0-fpm:
    try_files $uri =404;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    include fastcgi_params;
}

# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
location ~ /\.ht {
    deny all;
}

access_log /var/log/nginx/english4-u.com-access.log;
error_log  /var/log/nginx/english4-u.com-error.log error;

location = /favicon.ico { log_not_found off; access_log off; }
location = /robots.txt  { access_log off; log_not_found off; }

charset utf-8;

error_page 404 /index.php;}
</code>```

Can you help me with this?

Thank You.

答:
I dont know homestead and I would have posted this as comment but I don't have enough rep for that but maybe changing also the user ownership to www-data would work?

sudo chown www-data:www-data -R projectfolder

Then if it works you may have to change ownership for the storage folder if you are allowing file uploads.

Title: My css and javascript files not running

Body:
I installed Nginx server for my laravel project. But css and javascript file not working. Css and javascript file downloadable on server. For example http://myipaddress/css/bootstrap.css download the bootstrap.css file. I call the css file like <link href="{{ URL::asset('css/bootstrap.css') }}" rel="stylesheet"> like this.

My source code

My public folder permissions

/etc/nginx/sites-available/default looks like the following

# Default server configuration
#
server {
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;

# SSL configuration
#
 listen 443 ssl default_server;
 listen [::]:443 ssl default_server;
#
# Note: You should disable gzip for SSL traffic.
# See: https://bugs.debian.org/773332
#
# Read up on ssl_ciphers to ensure a secure configuration.
# See: https://bugs.debian.org/765782
#
# Self signed certs generated by the ssl-cert package
# Don't use them in a production server!
#
# include snippets/snakeoil.conf;

root /var/www/english4-u.com/public;

# Add index.php to the list if you are using PHP
index index.php index.html index.htm;

server_name english4-u.com;
ssl_certificate /etc/nginx/ssl/nginx.crt;
ssl_certificate_key /etc/nginx/ssl/nginx.key;

location / {
    # First attempt to serve request as file, then
    # as directory, then fall back to displaying a 404.
    try_files $uri $uri/ /index.php?$query_string;
}

# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
location ~ \.php$ {
#   include snippets/fastcgi-php.conf;
#
#   # With php7.0-cgi alone:
#   fastcgi_pass 127.0.0.1:9000;
#   # With php7.0-fpm:
    try_files $uri =404;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    include fastcgi_params;
}

# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
location ~ /\.ht {
    deny all;
}

access_log /var/log/nginx/english4-u.com-access.log;
error_log  /var/log/nginx/english4-u.com-error.log error;

location = /favicon.ico { log_not_found off; access_log off; }
location = /robots.txt  { access_log off; log_not_found off; }

charset utf-8;

error_page 404 /index.php;}

Can you help me with this?

Thank You.


问:
Return successively-yielded values as an array when generator is done
I would like to know if it is possible to return successively-yielded values as an array when the generator is done. This is what I have tried so far, where I add a return statement at the end of the generator and attempt to destructure the output:

```<code>function ajax(url) {
  fetch(url).then(data => data.json()).then(data => dataGen.next(data))
}

function* steps() {
  const beers = yield ajax('http://api.react.beer/v2/search?q=hops&type=beer');

  const wes = yield ajax('https://api.github.com/users/wesbos');

  const fatJoe = yield ajax('https://api.discogs.com/artists/51988');

  return [beers, wes, fatJoe]
}

const dataGen = steps();
const [beers, wes, fatJoe] = dataGen.next(); // kick it off
</code>```

However, none of the values are returned:

```<code>Uncaught ReferenceError: beers is not defined
Uncaught ReferenceError: wes is not defined
Uncaught ReferenceError: fatJoe is not defined
</code>```

答:
If interpret Question correctly you can use yield*, pass steps() call to Promise.all(), .then()

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Generators</title>

```
</div>
</div>
</p>

<p>Or <code>Promise.all()</code> without generator function</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Generators</title>
</head>
<body>
<script>

  function ajax(url) {
    return fetch(url).then(data => data.json()).then(data => data)
  }

  function steps() {
    return [
             ajax('data:application/json,[1]')
             , ajax('data:application/json,[2]')
             , ajax('data:application/json,[3]')
           ];
  }

  // kick it off
  Promise.all(steps())
  .then(([beers, wes, fatJoe]) =>
    console.log(beers, wes, fatJoe)
  )
</script>
</body>
</html></code>```

Body:
I would like to know if it is possible to return successively-yielded values as an array when the generator is done. This is what I have tried so far, where I add a return statement at the end of the generator and attempt to destructure the output:

function ajax(url) {
  fetch(url).then(data => data.json()).then(data => dataGen.next(data))
}

function* steps() {
  const beers = yield ajax('http://api.react.beer/v2/search?q=hops&type=beer');

  const wes = yield ajax('https://api.github.com/users/wesbos');

  const fatJoe = yield ajax('https://api.discogs.com/artists/51988');

  return [beers, wes, fatJoe]
}

const dataGen = steps();
const [beers, wes, fatJoe] = dataGen.next(); // kick it off

However, none of the values are returned:

Uncaught ReferenceError: beers is not defined
Uncaught ReferenceError: wes is not defined
Uncaught ReferenceError: fatJoe is not defined

Body:
If interpret Question correctly you can use yield*, pass steps() call to Promise.all(), .then()

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Generators</title>
</head>
<body>
<script>

  function ajax(url) {
    return fetch(url).then(data => data.json()).then(data => data)
  }

  function* steps() {
    yield* [
             ajax('data:application/json,[1]')
             , ajax('data:application/json,[2]')
             , ajax('data:application/json,[3]')
           ];
  }

  // kick it off
  Promise.all(steps())
  .then(([beers, wes, fatJoe]) =>
    console.log(beers, wes, fatJoe)
  )
</script>
</body>
</html>

Or Promise.all() without generator function

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Generators</title>
</head>
<body>
<script>

  function ajax(url) {
    return fetch(url).then(data => data.json()).then(data => data)
  }

  function steps() {
    return [
             ajax('data:application/json,[1]')
             , ajax('data:application/json,[2]')
             , ajax('data:application/json,[3]')
           ];
  }

  // kick it off
  Promise.all(steps())
  .then(([beers, wes, fatJoe]) =>
    console.log(beers, wes, fatJoe)
  )
</script>
</body>
</html>


问:
how to get input value inside label have active class
Hi i want to get input id value from label that have active class and i tried with this but only have undefined alert guys can you please tell me how i can do this thank you.

HTML:

```<code> <label class="btn btn-default active">
  <input type="radio" name="activity" id="{$base}p/handler/?handle=privmsg&output=html">
 Msgs</label>
 <label class="btn btn-default">
   <input type="radio" name="activity" id="{$base}p/handler/handle=notify&output=html">
 notify</label>
</code>```

JS:

```<code>g = $('label[class="btn btn-default active"]').next().attr('id');
    alert(g);
</code>```

答:
Only change this:

```<code>g = $('label[class="btn btn-default active"]').next().attr('id');
</code>```

to:

```<code>g = $('.active input[type="radio"]').attr('id');
</code>```

g = $('.active input[type="radio"]').attr('id');
console.log(g);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="btn btn-default active">
  <input type="radio" name="activity" id="{$base}p/handler/?handle=privmsg&output=html">
   Msgs
</label>
 <label class="btn btn-default">
   <input type="radio" name="activity" id="{$base}p/handler/handle=notify&output=html">
    notify
 </label></code>```

Body:
Hi i want to get input id value from label that have active class and i tried with this but only have undefined alert guys can you please tell me how i can do this thank you.

HTML:

  <input type="radio" name="activity" id="{$base}p/handler/?handle=privmsg&output=html">
 Msgs

   <input type="radio" name="activity" id="{$base}p/handler/handle=notify&output=html">
 notify

JS:

g = $('label[class="btn btn-default active"]').next().attr('id');
    alert(g);

Body:
Only change this:

g = $('label[class="btn btn-default active"]').next().attr('id');

to:

g = $('.active input[type="radio"]').attr('id');

g = $('.active input[type="radio"]').attr('id');
console.log(g);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="btn btn-default active">
  <input type="radio" name="activity" id="{$base}p/handler/?handle=privmsg&output=html">
   Msgs
</label>
 <label class="btn btn-default">
   <input type="radio" name="activity" id="{$base}p/handler/handle=notify&output=html">
    notify
 </label>


问:
How to auto layout an app for different devices.
Apologies in advance for the basic nature of this question. I'm happy to be redirected to a previously answered version of this question, but haven't found it yet.

I just finished up the majority of my first app, and am concerned I might have set it up in the wrong way.

My app looks "good" on an iphone7, but when I change the device to a 7+ there is empty space on the bottom and right edges of the view controllers, and when I run it on an iphone 5, the view doesn't fit.

Is there a way to make the view of my app automatically stretch/condense to any device? Or, is this way more complicated that I anticipated? I want to believe there's an easy solution but I haven't found it yet.

Thanks!

答:
if you support only portrait mode then.

First choose a base layout for design.As you have chosen iphone 7.
I choose iphone 7 plus.

Create some constant.

Why?

To create an aspect ratio to multiply with your every constraint's constant value you drew in iphone 7 layout.so that it will be calculate properly according to the device.

Like this.

```<code>var SCREEN_WIDTH = UIScreen.main.bounds.size.width
var SCREEN_HEIGHT = UIScreen.main.bounds.size.height
var BASE_SCREEN_HEIGHT:CGFloat = 736.0
var SCREEN_MAX_LENGTH = max(SCREEN_WIDTH, SCREEN_HEIGHT)
var ASPECT_RATIO_RESPECT_OF_7P = SCREEN_MAX_LENGTH / BASE_SCREEN_HEIGHT
</code>```

You can use mine too. if your base layout is iphone 7Plus.

How to use this?

Suppose you draw a top constraint about 10 for label in iphone 7 plus.
Then make a function and call it in viewDidLoad like this to support for all devices in portrait mode.

```<code>func updateConstraint() {
    topConstantOfYourLabel.constant = 10*ASPECT_RATIO_RESPECT_OF_7P
}
</code>```

if you support landscape mode

if you want to change the layout for landscape then you need to design for landscape.As most of your outlets just move here and there you only need to change top bottom left right constraint. So in that case , uninstall previous constraint and install another constraint and make it work only that size class.

There are lots of online tutorial about adaptive layout like this.

if you don't want to change the layout but properly calculate according to aspect ratio, then there is a function which triggers during orientation.

override func viewWillTransitionToSize(size: CGSize,
  withTransitionCoordinator coordinator:
  UIViewControllerTransitionCoordinator) {
    if UIDevice.currentDevice().orientation.isLandscape.boolValue {
        print("Landscape")
        imageView.image = UIImage(named: const2)
    } else {
        print("Portrait")
        imageView.image = UIImage(named: const)
    }
}

Apply logic in that function to support for all devices:)

Body:
if you support only portrait mode then.

First choose a base layout for design.As you have chosen iphone 7.
I choose iphone 7 plus.

Create some constant.

Why?

To create an aspect ratio to multiply with your every constraint's constant value you drew in iphone 7 layout.so that it will be calculate properly according to the device.

Like this.

var SCREEN_WIDTH = UIScreen.main.bounds.size.width
var SCREEN_HEIGHT = UIScreen.main.bounds.size.height
var BASE_SCREEN_HEIGHT:CGFloat = 736.0
var SCREEN_MAX_LENGTH = max(SCREEN_WIDTH, SCREEN_HEIGHT)
var ASPECT_RATIO_RESPECT_OF_7P = SCREEN_MAX_LENGTH / BASE_SCREEN_HEIGHT

You can use mine too. if your base layout is iphone 7Plus.

How to use this?

Suppose you draw a top constraint about 10 for label in iphone 7 plus.
Then make a function and call it in viewDidLoad like this to support for all devices in portrait mode.

func updateConstraint() {
    topConstantOfYourLabel.constant = 10*ASPECT_RATIO_RESPECT_OF_7P
}

if you support landscape mode

if you want to change the layout for landscape then you need to design for landscape.As most of your outlets just move here and there you only need to change top bottom left right constraint. So in that case , uninstall previous constraint and install another constraint and make it work only that size class.

There are lots of online tutorial about adaptive layout like this.

if you don't want to change the layout but properly calculate according to aspect ratio, then there is a function which triggers during orientation.

override func viewWillTransitionToSize(size: CGSize,
  withTransitionCoordinator coordinator:
  UIViewControllerTransitionCoordinator) {
    if UIDevice.currentDevice().orientation.isLandscape.boolValue {
        print("Landscape")
        imageView.image = UIImage(named: const2)
    } else {
        print("Portrait")
        imageView.image = UIImage(named: const)
    }
}

Apply logic in that function to support for all devices:)


问:
Why does a double free() not crash the program?
As per my understanding below program could have been crashed as freeing already freed memory but its not. Running on my Linux machine.</p>

```<code>#include <stdio.h>
#include <malloc.h>
int main(void) {
      int *ptr1 = NULL;
      ptr1 = malloc(100);
      free(ptr1);
      free(ptr1);
      printf("%d\n", *ptr1);
      return 0;
}
</code>```

答:
According to the definition of free, a double free achieves undefined behaviour:

7.20.3.2 The free function

The free function causes the space pointed to by ptr to be deallocated, that is, made available for further
  allocation. If ptr is a null pointer, no action occurs. Otherwise, if
  the argument does not match a pointer earlier returned by the calloc,
  malloc, or realloc function, or if the space has been deallocated by
  a call to free or realloc, the behavior is undefined.

And undefined behaviour itself is defined in the same standard as follows:

3.4.3 (1) undefined behavior

behavior, upon use of a nonportable or erroneous program construct or
  of erroneous data, for which this International Standard imposes no
  requirements NOTE Possible undefined behavior ranges from ignoring the
  situation completely with unpredictable results, to behaving during
  translation or program execution in a documented manner characteristic
  of the environment (with or without the issuance of a diagnostic
  message), to terminating a translation or execution (with the issuance
  of a diagnostic message)

So a program with undefined behaviour may "crash", but it also may not. It's undefined...

Body:
As per my understanding below program could have been crashed as freeing already freed memory but its not. Running on my Linux machine.

#include <stdio.h>
#include <malloc.h>
int main(void) {
      int *ptr1 = NULL;
      ptr1 = malloc(100);
      free(ptr1);
      free(ptr1);
      printf("%d\n", *ptr1);
      return 0;
}


问:
gvisBubbleChart with categories for shiny app
I'm looking for a versatile bubble chart.
In my shiny app it has to be able to adjust to two things:

It must be clickable. I need to read the selected bubble from the chart and use the selected input for other visualisations inside the app.

I have a categorial x-axis.

I was looking into gvisBubbleChart which seemed to fit very well, but it only responds to a numerical x-axis.

For example:

```<code>data <- data.frame(id = c(1,2,3,4,5),xvar = c("a","b","c","d","e"),yvar = c(7,2,5,8,1),sizevar = c(3,66,7,8,5),colorvar = rep(0,5))

plot(gvisBubbleChart(data,idvar = "id", xvar = "xvar", yvar = "yvar", sizevar = "sizevar",colorvar="colorvar"))
</code>```

Changes the xaxis to 1.5:6.0 instead of the string.

Is there a way to work around this? It seems that the input has to be numerical, I could not find a native option to turn this off.

I'm also very open to any other suggested packages which serve my needs, for ggplot I'm not sure if I can make the clickable part work?

答:
So I checked various sources, editing the googlevisBubble chart is possible with a lot of effort, too much for my case as this would be a very hard workaround.

Google Charts Bubble Charts categorical x and y axes instead of numeric

What I'm going to do is use plotly with ggplot for the dynamic input in my shiny app, the hole package looks very promising.

https://plot.ly/r/shinyapp-plotly-events/

Body:
I'm looking for a versatile bubble chart.
In my shiny app it has to be able to adjust to two things:

It must be clickable. I need to read the selected bubble from the chart and use the selected input for other visualisations inside the app.

I have a categorial x-axis.

I was looking into gvisBubbleChart which seemed to fit very well, but it only responds to a numerical x-axis.

For example:

data <- data.frame(id = c(1,2,3,4,5),xvar = c("a","b","c","d","e"),yvar = c(7,2,5,8,1),sizevar = c(3,66,7,8,5),colorvar = rep(0,5))

plot(gvisBubbleChart(data,idvar = "id", xvar = "xvar", yvar = "yvar", sizevar = "sizevar",colorvar="colorvar"))

Changes the xaxis to 1.5:6.0 instead of the string.

Is there a way to work around this? It seems that the input has to be numerical, I could not find a native option to turn this off.

I'm also very open to any other suggested packages which serve my needs, for ggplot I'm not sure if I can make the clickable part work?


问:
How can I manipulate this object in jQuery
```<code>jQuery(function () {
    $('#square a').click(function(e) {
    // How is the e object structured
    });
})
</code>```

I have a div with an id of square and links in that. When the links are clicked they trigger a game loop function. I need to know which id the click is coming from. There are five links within the square and each one has an id. Is there a better way to track this. Or should I have a function for each link with its own id but this doesn't seem DRY to me.

答:
Inside an event handler you can refer to the DOM element the event was triggered on with this:

```<code>$('#square a').click(function(e) {
    alert(this.id);
});
</code>```

So jQuery makes it very convient to access the element.

If you have to execute different code based on the ID, I suggest to create some kind of map:

```<code>var actions = {
    action1: function() {

    },
    action2: function() {

    },
    ...
}
</code>```

and then just execute the function from the map:

```<code>$('#square a').click(function(e) {
    actions[this.id]();
});
</code>```

Just make sure you give the elements meaningful IDs.

ContentLicense: CC BY-SA 2.5

Body:
jQuery(function () {
    $('#square a').click(function(e) {
    // How is the e object structured
    });
})

I have a div with an id of square and links in that. When the links are clicked they trigger a game loop function. I need to know which id the click is coming from. There are five links within the square and each one has an id. Is there a better way to track this. Or should I have a function for each link with its own id but this doesn't seem DRY to me.

Body:
Inside an event handler you can refer to the DOM element the event was triggered on with this:

$('#square a').click(function(e) {
    alert(this.id);
});

So jQuery makes it very convient to access the element.

If you have to execute different code based on the ID, I suggest to create some kind of map:

var actions = {
    action1: function() {

    },
    action2: function() {

    },
    ...
}

and then just execute the function from the map:

$('#square a').click(function(e) {
    actions[this.id]();
});

Just make sure you give the elements meaningful IDs.


问:
WebBrowser c# object : set google chrome as default browser
Using below code to capture screenshot of mindmap url:

```<code>using (WebBrowser browser = new WebBrowser())
            {
                browser.Width = 900;
                browser.Height = 900;
                browser.ScrollBarsEnabled = true;

                // This will be called when the page finishes loading
                browser.DocumentCompleted += Program.OnDocumentCompleted;

                browser.Navigate("https://app.mindmup.com/map/_free/2017/06/4e6750b0484011e7a155fd63d7b56500");

                // This prevents the application from exiting until
                // Application.Exit is called
                Application.Run();
            }
</code>```

However, mindmap url cannot be opened in IE hence not able to capture the screenshot. Can anyone please suggest how to set google chrome as the browser when using Web Browser object. Or some other code to capture screenshot

答:
You cannot change which browser does the WebBrowser use. However, there are some other solutions:

1. Using other Web Browsers

I would recommend CefSharp. It uses Chromium which is perfect for your project.

More about CefSharp: here

2. Force WebBrowser to run IE11

By default, Internet Explorer 7 is used by WebBrowser. Luckily, You may force it to choose a newer version.

Before loading your form, run the createRegistry() first. You can call it in Program.cs. If you want to restore the registry, run removeRegistry().

```<code>public static void createRegistry()
    {
        string filename = Process.GetCurrentProcess().MainModule.FileName;
        filename = filename.Substring(filename.LastIndexOf('\\') + 1, filename.Length - filename.LastIndexOf('\\') - 1);
        if (filename.Contains("vhost"))
            filename = filename.Substring(0, filename.IndexOf('.') + 1) + "exe";

            Registry.LocalMachine.OpenSubKey(@"SOFTWARE\WOW6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", true).SetValue(filename, 11001, RegistryValueKind.DWord);

            Registry.LocalMachine.OpenSubKey(@"SOFTWARE\WOW6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BEHAVIORS", true).SetValue(filename, 11001, RegistryValueKind.DWord);

            Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", true).SetValue(filename, 11001, RegistryValueKind.DWord);

            Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BEHAVIORS", true).SetValue(filename, 11001, RegistryValueKind.DWord);
    }

    public static void removeRegistry()
    {
        string filename = Process.GetCurrentProcess().MainModule.FileName;
        filename = filename.Substring(filename.LastIndexOf('\\') + 1, filename.Length - filename.LastIndexOf('\\') - 1);
        if (filename.Contains("vhost"))
            filename = filename.Substring(0, filename.IndexOf('.') + 1) + "exe";
        try
        {
            Registry.LocalMachine.OpenSubKey(@"SOFTWARE\WOW6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", true).DeleteValue(filename);
        }
        catch
        {

        }
        try
        {
            Registry.LocalMachine.OpenSubKey(@"SOFTWARE\WOW6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BEHAVIORS", true).DeleteValue(filename);
        }
        catch
        {

        }
        try
        {
            Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", true).DeleteValue(filename);
        }
        catch
        {

        }
        try
        {
            Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BEHAVIORS", true).DeleteValue(filename);
        }
        catch
        {

        }
    }
</code>```

Body:
Using below code to capture screenshot of mindmap url:

using (WebBrowser browser = new WebBrowser())
            {
                browser.Width = 900;
                browser.Height = 900;
                browser.ScrollBarsEnabled = true;

                // This will be called when the page finishes loading
                browser.DocumentCompleted += Program.OnDocumentCompleted;

                browser.Navigate("https://app.mindmup.com/map/_free/2017/06/4e6750b0484011e7a155fd63d7b56500");

                // This prevents the application from exiting until
                // Application.Exit is called
                Application.Run();
            }

However, mindmap url cannot be opened in IE hence not able to capture the screenshot. Can anyone please suggest how to set google chrome as the browser when using Web Browser object. Or some other code to capture screenshot

Body:
You cannot change which browser does the WebBrowser use. However, there are some other solutions:

1. Using other Web Browsers

I would recommend CefSharp. It uses Chromium which is perfect for your project.

More about CefSharp: here

2. Force WebBrowser to run IE11

By default, Internet Explorer 7 is used by WebBrowser. Luckily, You may force it to choose a newer version.

Before loading your form, run the createRegistry() first. You can call it in Program.cs. If you want to restore the registry, run removeRegistry().

public static void createRegistry()
    {
        string filename = Process.GetCurrentProcess().MainModule.FileName;
        filename = filename.Substring(filename.LastIndexOf('\\') + 1, filename.Length - filename.LastIndexOf('\\') - 1);
        if (filename.Contains("vhost"))
            filename = filename.Substring(0, filename.IndexOf('.') + 1) + "exe";

            Registry.LocalMachine.OpenSubKey(@"SOFTWARE\WOW6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", true).SetValue(filename, 11001, RegistryValueKind.DWord);

            Registry.LocalMachine.OpenSubKey(@"SOFTWARE\WOW6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BEHAVIORS", true).SetValue(filename, 11001, RegistryValueKind.DWord);

            Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", true).SetValue(filename, 11001, RegistryValueKind.DWord);

            Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BEHAVIORS", true).SetValue(filename, 11001, RegistryValueKind.DWord);
    }

    public static void removeRegistry()
    {
        string filename = Process.GetCurrentProcess().MainModule.FileName;
        filename = filename.Substring(filename.LastIndexOf('\\') + 1, filename.Length - filename.LastIndexOf('\\') - 1);
        if (filename.Contains("vhost"))
            filename = filename.Substring(0, filename.IndexOf('.') + 1) + "exe";
        try
        {
            Registry.LocalMachine.OpenSubKey(@"SOFTWARE\WOW6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", true).DeleteValue(filename);
        }
        catch
        {

        }
        try
        {
            Registry.LocalMachine.OpenSubKey(@"SOFTWARE\WOW6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BEHAVIORS", true).DeleteValue(filename);
        }
        catch
        {

        }
        try
        {
            Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", true).DeleteValue(filename);
        }
        catch
        {

        }
        try
        {
            Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BEHAVIORS", true).DeleteValue(filename);
        }
        catch
        {

        }
    }


问:
How to run Scala script using spark-submit (similarly to Python script)?
I try to execute a simple Scala script using Spark as described in the Spark Quick Start Tutorial. I have not troubles to execute the following Python code:

```<code>"""SimpleApp.py"""
from pyspark import SparkContext

logFile = "tmp.txt"  # Should be some file on your system
sc = SparkContext("local", "Simple App")
logData = sc.textFile(logFile).cache()

numAs = logData.filter(lambda s: 'a' in s).count()
numBs = logData.filter(lambda s: 'b' in s).count()

print "Lines with a: %i, lines with b: %i" % (numAs, numBs)
</code>```

I execute this code using the following command:

```<code>/home/aaa/spark/spark-2.1.0-bin-hadoop2.7/bin/spark-submit hello_world.py
</code>```

However, if I try to do the same using Scala, I have technical problems. In more detail, the code that I try to execute is:

```<code>* SimpleApp.scala */
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark.SparkConf

object SimpleApp {
  def main(args: Array[String]) {
    val logFile = "tmp.txt" // Should be some file on your system
    val conf = new SparkConf().setAppName("Simple Application")
    val sc = new SparkContext(conf)
    val logData = sc.textFile(logFile, 2).cache()
    val numAs = logData.filter(line => line.contains("a")).count()
    val numBs = logData.filter(line => line.contains("b")).count()
    println("Lines with a: %s, Lines with b: %s".format(numAs, numBs))
  }
}
</code>```

I try to execute it in the following way:

```<code>/home/aaa/spark/spark-2.1.0-bin-hadoop2.7/bin/spark-submit hello_world.scala
</code>```

As the result I get the following error message:

```<code>Error: Cannot load main class from JAR file
</code>```

Does anybody know what I am doing wrong?

答:
I want to add to @JacekLaskowski's an alternative solution I use sometimes for POC or tests purposes.

It would be to use the script.scala from inside the spark-shell with :load.

```<code>:load /path/to/script.scala
</code>```

You won't need to define a SparkContext/SparkSession as the script will use the variables defined in the scope of the REPL.

You also don't need to wrap the code in a Scala object.

PS: I consider this more as a hack and not to use for production purposes.

Body:
I try to execute a simple Scala script using Spark as described in the Spark Quick Start Tutorial. I have not troubles to execute the following Python code:

"""SimpleApp.py"""
from pyspark import SparkContext

logFile = "tmp.txt"  # Should be some file on your system
sc = SparkContext("local", "Simple App")
logData = sc.textFile(logFile).cache()

numAs = logData.filter(lambda s: 'a' in s).count()
numBs = logData.filter(lambda s: 'b' in s).count()

print "Lines with a: %i, lines with b: %i" % (numAs, numBs)

I execute this code using the following command:

/home/aaa/spark/spark-2.1.0-bin-hadoop2.7/bin/spark-submit hello_world.py

However, if I try to do the same using Scala, I have technical problems. In more detail, the code that I try to execute is:

* SimpleApp.scala */
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark.SparkConf

object SimpleApp {
  def main(args: Array[String]) {
    val logFile = "tmp.txt" // Should be some file on your system
    val conf = new SparkConf().setAppName("Simple Application")
    val sc = new SparkContext(conf)
    val logData = sc.textFile(logFile, 2).cache()
    val numAs = logData.filter(line => line.contains("a")).count()
    val numBs = logData.filter(line => line.contains("b")).count()
    println("Lines with a: %s, Lines with b: %s".format(numAs, numBs))
  }
}

I try to execute it in the following way:

/home/aaa/spark/spark-2.1.0-bin-hadoop2.7/bin/spark-submit hello_world.scala

As the result I get the following error message:

Error: Cannot load main class from JAR file

Does anybody know what I am doing wrong?

Body:
I want to add to @JacekLaskowski's an alternative solution I use sometimes for POC or tests purposes.

It would be to use the script.scala from inside the spark-shell with :load.

:load /path/to/script.scala

You won't need to define a SparkContext/SparkSession as the script will use the variables defined in the scope of the REPL.

You also don't need to wrap the code in a Scala object.

PS: I consider this more as a hack and not to use for production purposes.


问:
UIButton contentVerticalAlignment doesn't center button image
I created a UIButton programmatically and set its image, but the image just won't center vertically, it's always rendered at the bottom of the button.

Here is my code:

```<code>CGFloat logoutButtonSize = self.profileItem.detailView.frame.size.height;
CGFloat logoutButtonX = self.profileItem.detailView.frame.size.width - logoutButtonSize - 8;
CGRect logoutButtonFrame = CGRectMake(logoutButtonX, 0, logoutButtonSize, logoutButtonSize);
UIButton *logoutButton = [[UIButton alloc] initWithFrame:logoutButtonFrame];
[logoutButton setImage:[UIImage imageNamed:@"logout.png"] forState:UIControlStateNormal];
logoutButton.imageView.contentMode = UIViewContentModeCenter;
logoutButton.contentMode = UIViewContentModeCenter;
[logoutButton addTarget:self
                 action:@selector(confirmLogout)
       forControlEvents:UIControlEventTouchUpInside];
logoutButton.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
logoutButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
logoutButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
</code>```

After setting a distinct background color for the imageView of the button I can see that it's still aligned to the bottom:

(blue = button, red = image view)

Why is it not working?

答:
Point 1

AFAIK, UIControlContentVerticalAlignmentCenter & contentHorizontalAlignment is for text alignment and not for image....

Point 2

UIButton *logoutButton = [[UIButton alloc] initWithFrame:logoutButtonFrame]; will create basic button (like < iOS 6) opposed to Custom button. Below is how you should have button programmatically.

```<code>UIButton * logoutButton = [UIButton buttonWithType:UIButtonTypeCustom];
[logoutButton setBackgroundImage:[UIImage imageNamed:@"logout.png"] forControlEvents:UIControlEventTouchUpInside];
[logoutButton addTarget:self action:@selector(confirmLogout) forControlEvents:UIControlEventTouchUpInside];
[logoutButton setTitle:@"" forState:UIControlStateNormal];
logoutButton.frame = CGRectMake(logoutButtonX, 0, logoutButtonSize, logoutButtonSize);
[self.view addSubview: logoutButton];
</code>```

Now for image to adjust,

```<code>continueButton.imageView.contentMode = UIViewContentModeScaleAspectFit;
</code>```

You are done...

And last

Your code is not working because your UIButton is not Custom button.

Body:
I created a UIButton programmatically and set its image, but the image just won't center vertically, it's always rendered at the bottom of the button.

Here is my code:

CGFloat logoutButtonSize = self.profileItem.detailView.frame.size.height;
CGFloat logoutButtonX = self.profileItem.detailView.frame.size.width - logoutButtonSize - 8;
CGRect logoutButtonFrame = CGRectMake(logoutButtonX, 0, logoutButtonSize, logoutButtonSize);
UIButton *logoutButton = [[UIButton alloc] initWithFrame:logoutButtonFrame];
[logoutButton setImage:[UIImage imageNamed:@"logout.png"] forState:UIControlStateNormal];
logoutButton.imageView.contentMode = UIViewContentModeCenter;
logoutButton.contentMode = UIViewContentModeCenter;
[logoutButton addTarget:self
                 action:@selector(confirmLogout)
       forControlEvents:UIControlEventTouchUpInside];
logoutButton.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
logoutButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
logoutButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;

After setting a distinct background color for the imageView of the button I can see that it's still aligned to the bottom:

(blue = button, red = image view)

Why is it not working?

Body:
Point 1

AFAIK, UIControlContentVerticalAlignmentCenter & contentHorizontalAlignment is for text alignment and not for image....

Point 2

UIButton *logoutButton = [[UIButton alloc] initWithFrame:logoutButtonFrame]; will create basic button (like < iOS 6) opposed to Custom button. Below is how you should have button programmatically.

UIButton * logoutButton = [UIButton buttonWithType:UIButtonTypeCustom];
[logoutButton setBackgroundImage:[UIImage imageNamed:@"logout.png"] forControlEvents:UIControlEventTouchUpInside];
[logoutButton addTarget:self action:@selector(confirmLogout) forControlEvents:UIControlEventTouchUpInside];
[logoutButton setTitle:@"" forState:UIControlStateNormal];
logoutButton.frame = CGRectMake(logoutButtonX, 0, logoutButtonSize, logoutButtonSize);
[self.view addSubview: logoutButton];

Now for image to adjust,

continueButton.imageView.contentMode = UIViewContentModeScaleAspectFit;

You are done...

And last

Your code is not working because your UIButton is not Custom button.


问:
Change position of Angular component based on parent property
I have an angular 2 component that represents a simple control. It has a body and a footer. The user of the control interacts only with the <my-control> component, which passes a lot of the properties through to <the-body> and <the-footer>.

```<code>selector: 'my-control',
template: `
    <the-body
        [bodyProp1]="bodyProp1"
        [bodyProp2]="bodyProp2">
    </the-body>
    <the-footer
        [footerProp1]="footerProp1"
        [footerProp2]="footerProp2">
    </the-footer>`
</code>```

I'd like to be able to add a property to <my-control> that puts the footer above <the-body> rather than below it. I could do something like this:

```<code>selector: 'my-control',
template: `
    <the-footer
       *ngIf="footerPosition === 'top'"
       [footerProp1]="footerProp1"
       [footerProp2]="footerProp2">
    <the-body
       [bodyProp1]="bodyProp1"
       [bodyProp2]="bodyProp2">
    </the-body>
    <the-footer
        *ngIf="footerPosition === 'bottom'"
        [footerProp1]="footerProp1"
        [footerProp2]="footerProp2">
    </the-footer>`
</code>```

But I don't want to have to repeat the entire <the-footer> component again at the top. In the real code there are a lot of properties on it and it would be a maintenance problem to keep both <the-footer> components perfectly in sync.

Outside of messing with the CSS position values, is there a way to tell angular to reposition the <the-footer> component based on the value of the footerPosition property?

答:
You could create a  component that will render the <the-footer> component and try the below structure:

```<code>   <my-control>

   <Footer-Container *ngIf="footerPosition === top">
   </Footer-Container>

   <the-body>
   </the-body>

   <Footer-Container *ngIf="footerPosition === bottom">
   </Footer-Container>

   </my-control>
</code>```

hope this workaround would save you time to maintain rendering <the-footer> component at multiple places.

Body:
I have an angular 2 component that represents a simple control. It has a body and a footer. The user of the control interacts only with the <my-control> component, which passes a lot of the properties through to <the-body> and <the-footer>.

selector: 'my-control',
template: `
    <the-body
        [bodyProp1]="bodyProp1"
        [bodyProp2]="bodyProp2">
    </the-body>
    <the-footer
        [footerProp1]="footerProp1"
        [footerProp2]="footerProp2">
    </the-footer>`

I'd like to be able to add a property to <my-control> that puts the footer above <the-body> rather than below it. I could do something like this:

selector: 'my-control',
template: `
    <the-footer
       *ngIf="footerPosition === 'top'"
       [footerProp1]="footerProp1"
       [footerProp2]="footerProp2">
    <the-body
       [bodyProp1]="bodyProp1"
       [bodyProp2]="bodyProp2">
    </the-body>
    <the-footer
        *ngIf="footerPosition === 'bottom'"
        [footerProp1]="footerProp1"
        [footerProp2]="footerProp2">
    </the-footer>`

But I don't want to have to repeat the entire <the-footer> component again at the top. In the real code there are a lot of properties on it and it would be a maintenance problem to keep both <the-footer> components perfectly in sync.

Outside of messing with the CSS position values, is there a way to tell angular to reposition the <the-footer> component based on the value of the footerPosition property?

Body:
You could create a <Footer-Container> component that will render the <the-footer> component and try the below structure:

   <my-control>

   <Footer-Container *ngIf="footerPosition === top">
   </Footer-Container>

   <the-body>
   </the-body>

   <Footer-Container *ngIf="footerPosition === bottom">
   </Footer-Container>

   </my-control>

hope this workaround would save you time to maintain rendering <the-footer> component at multiple places.


答:
The e in your code is an event object. The docs for that are here. Within an event handler, this refers to the DOM element that you have hooked the handler to (not wrapped in a jQuery instance). So for instance:

```<code>jQuery(function ($) {
    $('#square a').click(function(e) {
        alert(this.href);
    });
});
</code>```

...would show the href of the link that was clicked.

Since click events bubble up the DOM, and they also have a default behavior on a elements (following the link), you may particularly be interested in event.stopPropagation (stop the event bubbling any further up the DOM) and event.preventDefault (prevent the default action). You can get the effect of calling both of those if you simply return false out of your event handler, but sometimes you only want to do one or the other.

Title: How can I manipulate this object in jQuery

Body:
The e in your code is an event object. The docs for that are here. Within an event handler, this refers to the DOM element that you have hooked the handler to (not wrapped in a jQuery instance). So for instance:

jQuery(function ($) {
    $('#square a').click(function(e) {
        alert(this.href);
    });
});

...would show the href of the link that was clicked.

Since click events bubble up the DOM, and they also have a default behavior on a elements (following the link), you may particularly be interested in event.stopPropagation (stop the event bubbling any further up the DOM) and event.preventDefault (prevent the default action). You can get the effect of calling both of those if you simply return false out of your event handler, but sometimes you only want to do one or the other.


问:
Behaviour of arr[i] = i++ and i = i + 1 statements in C and C++
In the C and C++ languages, the arr[i] = i++; statement invokes undefined behavior. Why does the statement i = i + 1; not invoke undefined behavior?

答:
In your example a [i] = i++, if i = 3 for example, do you think a [i] is evaluated first, or i++? In one case, the value 3 would be stored in a [3], in the other case, it would be stored in a [4]. It's obvious that we have a problem here. No sane person would dare writing that code unless they found a guarantee what exactly will happen here. (Java gives that guarantee).

What would you think could be a problem with i = i + 1? The language must read i first to calculate i+1, then store that result. There is nothing here that could be wrong. Same with a [i] = i+1. Evaluating i+1, unlike i++, doesn't change i. So if i = 3, the number 4 must be stored in a [3].

Various languages have various rules to fix the problem with a [i] = i++. Java defines what happens: Expressions are evaluated left to right including their side effects. C defines it as undefined behaviour. C++ doesn't make it undefined behaviour but just unspecified. It says that either a[i] or i++ is evaluated first, and the other one next, but it doesn't say which one. So unlike C where anything can happen, C++ defines that only one of two things can happen. Obviously that's one thing too many to be acceptable in your code.