问:
Push Notifications are delivered but didReceiveRemoteNotification is never called Swift
I have successfully implemented push notifications in my two related apps via FCM and while trying to implement some logic to increment badge number on receiving the notification.

I realized that didReceiveRemoteNotificationdelegate method is not called at all as I don't get any prints out of it, but I do get prints from willPresent notificationand didReceive response. So setting UIApplication.shared.applicationIconBadgeNumber in didFinishLaunchingWithOptionshas no effect, but setting in it didReceive responsedoes.

Following the documentation didReceiveRemoteNotification should be called but I never get prints out of it when a notification arrives.

I tried commenting out the whole didReceiveRemoteNotificationmethod and notifications are still delivered.

Why is it so? I guess I didn't really understand who's handling messaging in this set up. Can you please help me clarifying it?

AppDelegate methods:

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()
//                        UIApplication.shared.applicationIconBadgeNumber = 1
                        AppDelegate.badgeCountNumber = 0
                        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()
//            UIApplication.shared.applicationIconBadgeNumber = 1
            UIApplication.shared.applicationIconBadgeNumber = 0
            print("didFinishLaunchingWithOptions iOS 9: Successfully registered for APNs")
        }
        // 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>```

didReceiveRemoteNotification:

```<code> // foreground
        func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
            print("didReceiveRemoteNotification: Received new push Notification")
            // If you are receiving a notification message while your app is in the background,
            // this callback will not be fired till the user taps on the notification launching the application.
            // TODO: Handle data of notification

            // With swizzling disabled you must let Messaging know about the message, for Analytics
            Messaging.messaging().appDidReceiveMessage(userInfo)
            AppDelegate.badgeCountNumber += userInfo["badge"] as! Int
            print("AppDelegate.badgeCountNumber is : \(String(describing: AppDelegate.badgeCountNumber))")
//            UIApplication.shared.applicationIconBadgeNumber = AppDelegate.badgeCountNumber
            UIApplication.shared.applicationIconBadgeNumber =  10//AppDelegate.badgeCountNumber
            // Print full message.
            print("didReceiveRemoteNotification: Push notificationMessage is: \(userInfo)")
        }

        // background
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                     fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        print("didReceiveRemoteNotification with handler : Received new push Notification while in background")
        // If you are receiving a notification message while your app is in the background,
        // this callback will not be fired till the user taps on the notification launching the application.
        // TODO: Handle data of notification

        // With swizzling disabled you must let Messaging know about the message, for Analytics
        Messaging.messaging().appDidReceiveMessage(userInfo)
        if let messageID = userInfo[ userDetails.fcmToken] { // working for looged in
            print("didReceiveRemoteNotification: Message ID: \(messageID)")
        }

        // Print full message.
        print("didReceiveRemoteNotification: Push notificationMessage is: \(userInfo)")
        AppDelegate.badgeCountNumber += userInfo["badge"] as! Int
        print("AppDelegate.badgeCountNumber is : \(String(describing: AppDelegate.badgeCountNumber))")
        UIApplication.shared.applicationIconBadgeNumber +=  userInfo["badge"] as! Int
        completionHandler(UIBackgroundFetchResult.newData)
    }
</code>```

答:
I finally found the solution. Alert needs"content_available": true to be set in the alert definition from the post sending funtion from App2 to App1 or else  notifications get delivered but 'didReceiveRemoteNotification` is not called and you can't use 'userInfo'. Hope this will help others as I haven't found much info about this problem. If you're setting the notification with Postman or similars check here didReceiveRemoteNotification function doesn't called with FCM notification server as that's the only post I found on this problem and solved mine.
Thanks to @Ranjani for trying helping me.

```<code>let postParams: [String : Any] = [
                "to": receiverToken,
                "notification": [
                    "badge" : 1,
                    "body": body,
                    "title": title,
                    "subtitle": subtitle,
                    "sound" : true, // or specify audio name to play
                    "content_available": true, // this will call didReceiveRemoteNotification in receiving app, else won't work
                    "priority": "high"
                ],
                "data" : [
                    "data": "ciao",
            ]
                ]
</code>```

Body:
I have successfully implemented push notifications in my two related apps via FCM and while trying to implement some logic to increment badge number on receiving the notification.

I realized that didReceiveRemoteNotificationdelegate method is not called at all as I don't get any prints out of it, but I do get prints from willPresent notificationand didReceive response. So setting UIApplication.shared.applicationIconBadgeNumber in didFinishLaunchingWithOptionshas no effect, but setting in it didReceive responsedoes.

Following the documentation didReceiveRemoteNotification should be called but I never get prints out of it when a notification arrives.

I tried commenting out the whole didReceiveRemoteNotificationmethod and notifications are still delivered.

Why is it so? I guess I didn't really understand who's handling messaging in this set up. Can you please help me clarifying it?

AppDelegate methods:

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()
//                        UIApplication.shared.applicationIconBadgeNumber = 1
                        AppDelegate.badgeCountNumber = 0
                        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()
//            UIApplication.shared.applicationIconBadgeNumber = 1
            UIApplication.shared.applicationIconBadgeNumber = 0
            print("didFinishLaunchingWithOptions iOS 9: Successfully registered for APNs")
        }
        // 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
    }

didReceiveRemoteNotification:

 // foreground
        func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
            print("didReceiveRemoteNotification: Received new push Notification")
            // If you are receiving a notification message while your app is in the background,
            // this callback will not be fired till the user taps on the notification launching the application.
            // TODO: Handle data of notification

            // With swizzling disabled you must let Messaging know about the message, for Analytics
            Messaging.messaging().appDidReceiveMessage(userInfo)
            AppDelegate.badgeCountNumber += userInfo["badge"] as! Int
            print("AppDelegate.badgeCountNumber is : \(String(describing: AppDelegate.badgeCountNumber))")
//            UIApplication.shared.applicationIconBadgeNumber = AppDelegate.badgeCountNumber
            UIApplication.shared.applicationIconBadgeNumber =  10//AppDelegate.badgeCountNumber
            // Print full message.
            print("didReceiveRemoteNotification: Push notificationMessage is: \(userInfo)")
        }

        // background
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                     fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        print("didReceiveRemoteNotification with handler : Received new push Notification while in background")
        // If you are receiving a notification message while your app is in the background,
        // this callback will not be fired till the user taps on the notification launching the application.
        // TODO: Handle data of notification

        // With swizzling disabled you must let Messaging know about the message, for Analytics
        Messaging.messaging().appDidReceiveMessage(userInfo)
        if let messageID = userInfo[ userDetails.fcmToken] { // working for looged in
            print("didReceiveRemoteNotification: Message ID: \(messageID)")
        }

        // Print full message.
        print("didReceiveRemoteNotification: Push notificationMessage is: \(userInfo)")
        AppDelegate.badgeCountNumber += userInfo["badge"] as! Int
        print("AppDelegate.badgeCountNumber is : \(String(describing: AppDelegate.badgeCountNumber))")
        UIApplication.shared.applicationIconBadgeNumber +=  userInfo["badge"] as! Int
        completionHandler(UIBackgroundFetchResult.newData)
    }

Body:
I finally found the solution. Alert needs"content_available": true to be set in the alert definition from the post sending funtion from App2 to App1 or else  notifications get delivered but 'didReceiveRemoteNotification` is not called and you can't use 'userInfo'. Hope this will help others as I haven't found much info about this problem. If you're setting the notification with Postman or similars check here didReceiveRemoteNotification function doesn't called with FCM notification server as that's the only post I found on this problem and solved mine.
Thanks to @Ranjani for trying helping me.

let postParams: [String : Any] = [
                "to": receiverToken,
                "notification": [
                    "badge" : 1,
                    "body": body,
                    "title": title,
                    "subtitle": subtitle,
                    "sound" : true, // or specify audio name to play
                    "content_available": true, // this will call didReceiveRemoteNotification in receiving app, else won't work
                    "priority": "high"
                ],
                "data" : [
                    "data": "ciao",
            ]
                ]


来源: stackexchange

问:
WPF - Is it possible to (programmatically) disable multi-touch?
I have a problem with WPF application/presentation for Tablet PC with (multi-) touch screen. One "slide" of the presentation consists of Canvas on background and of a small UserControl. This UserControl is invisible at start, but whenever user touches the screen, it becomes visible and if user moves his finger, the control moves accordingly ("following" the finger, like a cursor). Then, when user stops touching the screen, the control becomes invisible again.

This is not very hard to do using the TouchDown, TouchUp and TouchMove event handlers and it works fine if user touches the screen with just one finger. However, when user holds one finger on position X (e.g. canvas coordinates [100,100]) and another finger on position Y (e.g. [500, 100]), the UserControl starts jumping between positions X and Y, which doesn't look very well...

Now I'd like the screen to react only to one touch at the time, which I can do in operating system (Windows 7) using Control Panel -> Pen and Touch -> Touch by unchecking item "Enable multi-touch gestures and inking".

This works fine, exactly as I want it to, unfortunately it's not very convenient, because sometimes I need to use the multi-touch and I can't change it every time I decide to use the application...

That's why I'd like to ask if there is any way how to disable the multi-touch programmaticaly, in the application (or just in WPF UserControl) where I need it. Thanks a lot in advance for any help.

答:
You can use a boolean eg. IsCurrentTouched, set it true if user touches and the control is shown, and set it back to false when the touch is released.

While IsCurrentTouched is true don't react to other touches. So you are able to use multitouch only when needed ;-)

ContentLicense: CC BY-SA 3.0


问:
RequestAnimationFrame doesn't work in simple canvas
Here is simple code. Arc works for sure but when I try to put requestAnimationFrame in function whole function just doesn't work.

I did nothing because I am doing it from Chris Courses canvas course. Exactly same code as his.

```<code>            var canvas = document.querySelector('canvas');
            canvas.width = window.innerWidth;
            canvas.height = window.innerHeight;
            var ctx = canvas.getContext('2d');

            var x = 200;
            function animate(){
            requestAnimationFrame(animate);
            ctx.beginPath();
            ctx.arc(x, 200, 30, 0, Math.PI * 2, false);
            ctx.strokeStyle = 'blue';
            ctx.stroke();
            console.log('F');
            x =+ 1;
            }
</code>```

        <meta charset="utf-8"/>

        <canvas>

        </canvas>

```

答:
You need to call the animate function at least once outside of the function to initialize the start of it. This can be another requestAnimationFrame(animate), animate(), or a self invoking function.

```<code>function animate(){
  // The function body
  requestAnimationFrame(animate);
}

animate();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Here is simple code. Arc works for sure but when I try to put requestAnimationFrame in function whole function just doesn't work.

I did nothing because I am doing it from Chris Courses canvas course. Exactly same code as his.

            var canvas = document.querySelector('canvas');
            canvas.width = window.innerWidth;
            canvas.height = window.innerHeight;
            var ctx = canvas.getContext('2d');

            var x = 200;
            function animate(){
            requestAnimationFrame(animate);
            ctx.beginPath();
            ctx.arc(x, 200, 30, 0, Math.PI * 2, false);
            ctx.strokeStyle = 'blue';
            ctx.stroke();
            console.log('F');
            x =+ 1;
            }

        <meta charset="utf-8"/>

        <canvas>

        </canvas>

Body:
You need to call the animate function at least once outside of the function to initialize the start of it. This can be another requestAnimationFrame(animate), animate(), or a self invoking function.

function animate(){
  // The function body
  requestAnimationFrame(animate);
}

animate();


问:
Is it possible to escape all the parameters in multiple routes at once?
I have a router which has multiple routes. Currently, I am escaping every parameter being passed to the method separately in the method itself.

I need to escape all the parameters which are being passed in the URL for security purpose.

```<code>class MyRouter extends Backbone.Router
   routes:
     "student/:id/:name"         :        "student"
     "teacher/:tid/:tname"       :        "teacher"
     "teacher/:tid/:tname/share" :        "teacher_share"

  student: (id, name) ->
    id = _.escape(id)
    name = _.escape(name)
    #do stuff

  teacher: (tid, tname) ->
    tid = _.escape(tid)
    tname = _.escape(tname)
    #do stuff

  teacher_share: (tid, tname) ->
    tid = _.escape(tid)
    tname = _.escape(tname)
    #do stuff
</code>```

Is it possible to escape all the parameters in all the routes at once, so that I don't have to explicitly escape them in every respective method?

答:
You can override execute

execute router.execute(callback, args, name)
  This method is called internally within the router, whenever a route matches and its corresponding callback is about to be executed. Return false from execute to cancel the current transition. Override it to perform custom parsing or wrapping of your routes, for example, to parse query strings before handing them to your route callback, like so:

```<code>var Router = Backbone.Router.extend({
  execute: function(callback, args, name) {
    if (!loggedIn) {
      goToLogin();
      return false;
    }
    args.push(parseQueryString(args.pop()));
    if (callback) callback.apply(this, args);
  }
});
</code>```

Body:
I have a router which has multiple routes. Currently, I am escaping every parameter being passed to the method separately in the method itself.

I need to escape all the parameters which are being passed in the URL for security purpose.

class MyRouter extends Backbone.Router
   routes:
     "student/:id/:name"         :        "student"
     "teacher/:tid/:tname"       :        "teacher"
     "teacher/:tid/:tname/share" :        "teacher_share"

  student: (id, name) ->
    id = _.escape(id)
    name = _.escape(name)
    #do stuff

  teacher: (tid, tname) ->
    tid = _.escape(tid)
    tname = _.escape(tname)
    #do stuff

  teacher_share: (tid, tname) ->
    tid = _.escape(tid)
    tname = _.escape(tname)
    #do stuff

Is it possible to escape all the parameters in all the routes at once, so that I don't have to explicitly escape them in every respective method?

Body:
You can override execute

execute router.execute(callback, args, name)
  This method is called internally within the router, whenever a route matches and its corresponding callback is about to be executed. Return false from execute to cancel the current transition. Override it to perform custom parsing or wrapping of your routes, for example, to parse query strings before handing them to your route callback, like so:

var Router = Backbone.Router.extend({
  execute: function(callback, args, name) {
    if (!loggedIn) {
      goToLogin();
      return false;
    }
    args.push(parseQueryString(args.pop()));
    if (callback) callback.apply(this, args);
  }
});


问:
How to limit Azure Application Insights to only log custom events in dotnet core project?
I am using an dotnet core api project and have enables it with Azure Application Insight, a loots of data is been sent to Microsoft Azure, how could I limit it so it only sents my custome TrackEvent and disable the rest. Am I able to cofigure it using appsettings.json or programmatically?</p>

答:
This might happen when you add App Insights using the build in function provide by Visual Studio.
If you just want to log using App Insights and not send all the telemetry data you can do that by simply adding a few things.

In the Program.cs do this

```<code>public static IWebHostBuilder CreateWebHostBuilder(String[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .ConfigureLogging((context, logging) =>
            {
                var instrumentationKey = context.Configuration.GetSection("ApplicationInsights:InstrumentationKey").Value;

                if (String.IsNullOrWhiteSpace(instrumentationKey))
                {
                    return;
                }

                // When not in development, remove other loggers like console, debug, event source etc.
                // and only use ApplicationInsights logging
                if (!context.HostingEnvironment.IsDevelopment())
                {
                    logging.ClearProviders();
                }

                logging.AddApplicationInsights(instrumentationKey);
            });
</code>```

In your code wherever you want to use it, just inject a logger

```<code>    private readonly Repository _Repository = null;

    public MyController(Repository repository, ILogger<MyController> logger)
    {
        this._Repository = repository ?? throw new ArgumentNullException("repository");
        this._Logger = logger ?? throw new ArgumentNullException("logger");
    }
</code>```

And use it like,

```<code>_Logger.LogError(exception, errorMessage);
</code>```

For reference Microsoft Docs

Body:
This might happen when you add App Insights using the build in function provide by Visual Studio.
If you just want to log using App Insights and not send all the telemetry data you can do that by simply adding a few things.

In the Program.cs do this

public static IWebHostBuilder CreateWebHostBuilder(String[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .ConfigureLogging((context, logging) =>
            {
                var instrumentationKey = context.Configuration.GetSection("ApplicationInsights:InstrumentationKey").Value;

                if (String.IsNullOrWhiteSpace(instrumentationKey))
                {
                    return;
                }

                // When not in development, remove other loggers like console, debug, event source etc.
                // and only use ApplicationInsights logging
                if (!context.HostingEnvironment.IsDevelopment())
                {
                    logging.ClearProviders();
                }

                logging.AddApplicationInsights(instrumentationKey);
            });

In your code wherever you want to use it, just inject a logger

    private readonly Repository _Repository = null;

    public MyController(Repository repository, ILogger<MyController> logger)
    {
        this._Repository = repository ?? throw new ArgumentNullException("repository");
        this._Logger = logger ?? throw new ArgumentNullException("logger");
    }

And use it like,

_Logger.LogError(exception, errorMessage);

For reference Microsoft Docs


问:
Checking logged-in user info on CakePHP when using a custom auth adapter
I'm using this JWTAuth adapter to use JWT authentication instead of cookie-based auth in my CakePHP 2.8 app. It works great, except for one hitch:

Normally for one of my REST endpoints, I can use $this->Auth->user("id") to get the currently logged-in users' ID.

When I try to make a controller action accessible to non-members using $this->Auth->allow(), a problem occurs. If I do this, using $this->Auth->loggedIn() in the controller returns false, meaning I can not add additional logic for logged-in users.

When using standard cookie auth:

$this->Auth->user('id') is available in
Controller::beforeFilter().

$this->Auth->loggedIn() is true in
Controller::beforeFilter().

$this->Auth->user('id') is available in controller actions, public
and members-only.

$this->Auth->loggedIn() is true in controller actions, public
and members-only.

When using JWT auth:

$this->Auth->user('id') is null in Controller::beforeFilter().

$this->Auth->loggedIn() is false in
Controller::beforeFilter().

$this->Auth->user('id') is available in members-only controller actions, and null in public controller actions.

$this->Auth->loggedIn() is true in members-only controller actions, and false in public controller actions.

Is there any way I can get Auth to include information returned by the JWTAuth component on actions that have been made public by $this->Auth->allow()?

Example controller here:

```<code>public function visible(){
    // This will always be false, even if a valid JWT token is sent
    $this->set("loggedIn", $this->Auth->loggedIn());
}

public function members_only(){
    // This will be unavailable if not logged in, and a true if logged in
    $this->set("loggedIn", $this->Auth->loggedIn());
}

public function beforeFilter($options = array()){
    parent::beforeFilter();

    $this->Auth->allow("visible");
}
</code>```

And for reference, my AppController::components array;

```<code>public $components = array(
    'DebugKit.Toolbar',
    'Auth' => array(
        'authorize' => array(
            'Actions' => array(
                'actionPath' => 'controllers'
            ),
        ),
        'authenticate' => array(
            'Form' => array(
                'fields' => array('username' => 'email'),
                'contain' => array(
                    'UserProfile',
                )
            ),
            'JwtAuth.JwtToken' => array(
                'fields' => array(
                    'username' => 'email',
                    'token' => 'password',
                ),
                'header' => 'AuthToken',
                'userModel' => 'User',
            ),
        ),
        'unauthorizedRedirect' => false
    ),
    "Acl",
    "RequestHandler",
    "Session"
);
</code>```

答:
I'm a bit late, but I found a solution to this problem, but (warning!) it involved updating the code for AuthComponent.

I took a copy of Lib/Controller/Component/AuthComponent.php and placed it under app/Controller/Component/AuthComponent.php.

I then added one line to the file:

```<code>public function startup(Controller $controller) {
    $methods = array_flip(array_map('strtolower', $controller->methods));
    $action = strtolower($controller->request->params['action']);

    // One-line modification from the ordinary CakePHP file.
    // This lets us have info on the logged-in user in public actions when using stateless auth.
    $this->_getUser();
</code>```

Voila, you can now access user info on the server while accessing a non-protected controller function with stateless auth!

Body:
I'm using this JWTAuth adapter to use JWT authentication instead of cookie-based auth in my CakePHP 2.8 app. It works great, except for one hitch:

Normally for one of my REST endpoints, I can use $this->Auth->user("id") to get the currently logged-in users' ID.

When I try to make a controller action accessible to non-members using $this->Auth->allow(), a problem occurs. If I do this, using $this->Auth->loggedIn() in the controller returns false, meaning I can not add additional logic for logged-in users.

When using standard cookie auth:

$this->Auth->user('id') is available in
Controller::beforeFilter().

$this->Auth->loggedIn() is true in
Controller::beforeFilter().

$this->Auth->user('id') is available in controller actions, public
and members-only.

$this->Auth->loggedIn() is true in controller actions, public
and members-only.

When using JWT auth:

$this->Auth->user('id') is null in Controller::beforeFilter().

$this->Auth->loggedIn() is false in
Controller::beforeFilter().

$this->Auth->user('id') is available in members-only controller actions, and null in public controller actions.

$this->Auth->loggedIn() is true in members-only controller actions, and false in public controller actions.

Is there any way I can get Auth to include information returned by the JWTAuth component on actions that have been made public by $this->Auth->allow()?

Example controller here:

public function visible(){
    // This will always be false, even if a valid JWT token is sent
    $this->set("loggedIn", $this->Auth->loggedIn());
}

public function members_only(){
    // This will be unavailable if not logged in, and a true if logged in
    $this->set("loggedIn", $this->Auth->loggedIn());
}

public function beforeFilter($options = array()){
    parent::beforeFilter();

    $this->Auth->allow("visible");
}

And for reference, my AppController::components array;

public $components = array(
    'DebugKit.Toolbar',
    'Auth' => array(
        'authorize' => array(
            'Actions' => array(
                'actionPath' => 'controllers'
            ),
        ),
        'authenticate' => array(
            'Form' => array(
                'fields' => array('username' => 'email'),
                'contain' => array(
                    'UserProfile',
                )
            ),
            'JwtAuth.JwtToken' => array(
                'fields' => array(
                    'username' => 'email',
                    'token' => 'password',
                ),
                'header' => 'AuthToken',
                'userModel' => 'User',
            ),
        ),
        'unauthorizedRedirect' => false
    ),
    "Acl",
    "RequestHandler",
    "Session"
);

Body:
I'm a bit late, but I found a solution to this problem, but (warning!) it involved updating the code for AuthComponent.

I took a copy of Lib/Controller/Component/AuthComponent.php and placed it under app/Controller/Component/AuthComponent.php.

I then added one line to the file:

public function startup(Controller $controller) {
    $methods = array_flip(array_map('strtolower', $controller->methods));
    $action = strtolower($controller->request->params['action']);

    // One-line modification from the ordinary CakePHP file.
    // This lets us have info on the logged-in user in public actions when using stateless auth.
    $this->_getUser();

Voila, you can now access user info on the server while accessing a non-protected controller function with stateless auth!


问:
Vectorize multi-dimensional array population on octave
This is my actual code:

```<code>Lr = linspace(100,300,10);
vi = linspace(10,30,10);
vf = linspace(10,30,10);
b = linspace(0.5,1.2,10);
h = linspace(0.3,0.8,10);
Rc = [1000, 1500, 2000, 2500, 3000, 3500;
      29, 22.4, 17.3, 13.4, 10.4, 8];
rti = randi(5, 10, 1, 10, 10, 10, 10);
for kk = 1:rows(Lr)
  for jj = 1:length(vi)
    for ll = 1:length(vf)
      for mm = 1:length(b)
        for nn = 1:length(h)
          ratt(kk,1,jj,ll,mm,nn) = Rc(2,rti(kk,1,jj,ll,mm,nn));
        endfor
      endfor
    endfor
  endfor
endfor
</code>```

In this example, all the vectors are of length 10, but in the real code, they can be from 1 to 100.
How can I remove all these loops?

答:
Get all values to ratt from Rc as a 1D array.

Reshape ratt to a 6D array as in the original code.

Code:

```<code>ratt = Rc(2, rti(1:rows(Lr), 1, 1:length(vi), 1:length(vf), 1:length(b), 1:length(h)));
ratt = reshape(ratt, [rows(Lr), 1, length(vi), length(vf), length(b), length(h)]);
</code>```

Testing: To test the equality and speed of the vectorized and non-vectorized codes I wrote the following code:

```<code>Lr = linspace(100,300,10);
vi = linspace(10,30,10);
vf = linspace(10,30,10);
b = linspace(0.5,1.2,10);
h = linspace(0.3,0.8,10);
Rc = [1000, 1500, 2000, 2500, 3000, 3500;
      29, 22.4, 17.3, 13.4, 10.4, 8];
rti = randi(5, 10, 1, 10, 10, 10, 10);

disp('Non-vectorized:')
tic
for kk = 1:rows(Lr)
  for jj = 1:length(vi)
    for ll = 1:length(vf)
      for mm = 1:length(b)
        for nn = 1:length(h)
          ratt(kk,1,jj,ll,mm,nn) = Rc(2,rti(kk,1,jj,ll,mm,nn));
        endfor
      endfor
    endfor
  endfor
endfor
toc

disp('')

disp('Vectorized:')
tic
ratt1 = Rc(2, rti(1:rows(Lr), 1, 1:length(vi), 1:length(vf), 1:length(b), 1:length(h)));
ratt1 = reshape(ratt1, [rows(Lr), 1, length(vi), length(vf), length(b), length(h)]);
toc

disp('')

if(isequal(ratt,ratt1))
  disp('ratt is equal to ratt1!')
else
  disp('ratt is not equal to ratt1!')
endif
</code>```

Output:

```<code>Non-vectorized:
Elapsed time is 0.16697 seconds.

Vectorized:
Elapsed time is 0.000309944 seconds.

ratt is equal to ratt1!
</code>```

Body:
This is my actual code:

Lr = linspace(100,300,10);
vi = linspace(10,30,10);
vf = linspace(10,30,10);
b = linspace(0.5,1.2,10);
h = linspace(0.3,0.8,10);
Rc = [1000, 1500, 2000, 2500, 3000, 3500;
      29, 22.4, 17.3, 13.4, 10.4, 8];
rti = randi(5, 10, 1, 10, 10, 10, 10);
for kk = 1:rows(Lr)
  for jj = 1:length(vi)
    for ll = 1:length(vf)
      for mm = 1:length(b)
        for nn = 1:length(h)
          ratt(kk,1,jj,ll,mm,nn) = Rc(2,rti(kk,1,jj,ll,mm,nn));
        endfor
      endfor
    endfor
  endfor
endfor

In this example, all the vectors are of length 10, but in the real code, they can be from 1 to 100.
How can I remove all these loops?

Body:
Get all values to ratt from Rc as a 1D array.

Reshape ratt to a 6D array as in the original code.

Code:

ratt = Rc(2, rti(1:rows(Lr), 1, 1:length(vi), 1:length(vf), 1:length(b), 1:length(h)));
ratt = reshape(ratt, [rows(Lr), 1, length(vi), length(vf), length(b), length(h)]);

Testing: To test the equality and speed of the vectorized and non-vectorized codes I wrote the following code:

Lr = linspace(100,300,10);
vi = linspace(10,30,10);
vf = linspace(10,30,10);
b = linspace(0.5,1.2,10);
h = linspace(0.3,0.8,10);
Rc = [1000, 1500, 2000, 2500, 3000, 3500;
      29, 22.4, 17.3, 13.4, 10.4, 8];
rti = randi(5, 10, 1, 10, 10, 10, 10);

disp('Non-vectorized:')
tic
for kk = 1:rows(Lr)
  for jj = 1:length(vi)
    for ll = 1:length(vf)
      for mm = 1:length(b)
        for nn = 1:length(h)
          ratt(kk,1,jj,ll,mm,nn) = Rc(2,rti(kk,1,jj,ll,mm,nn));
        endfor
      endfor
    endfor
  endfor
endfor
toc

disp('')

disp('Vectorized:')
tic
ratt1 = Rc(2, rti(1:rows(Lr), 1, 1:length(vi), 1:length(vf), 1:length(b), 1:length(h)));
ratt1 = reshape(ratt1, [rows(Lr), 1, length(vi), length(vf), length(b), length(h)]);
toc

disp('')

if(isequal(ratt,ratt1))
  disp('ratt is equal to ratt1!')
else
  disp('ratt is not equal to ratt1!')
endif

Output:

Non-vectorized:
Elapsed time is 0.16697 seconds.

Vectorized:
Elapsed time is 0.000309944 seconds.

ratt is equal to ratt1!


问:
Does anyone know how to fix this weird cv2.error: OpenCV(4.1.0)?
Ok. I have got a "simple" homework from my teacher. Homework was about just changing lanes of command from python.exe .\AgeGender.py --input .\sample.jpg to python.exe .\AgeGender.py --input .\test.jpg

Link to files library: https://drive.google.com/file/d/1gvIhxmFPvEcbDcPoyjnkcjuxNiiXD1FY/view?usp=sharing

From the beging. Teacher said that all what I have to do is any terminal to run this. Well it turns out I had to learn how to run scripts from cmd after 2 hours of fighting and trying to run this AgeGender.py. Of course at the begginig there was no way to run python.exe from windows command promt so I had to find a way to put all files in to pycharm scripts folder ONLY to find out that script is wrongly written and that I have to find a way to fix it...

```<code>import cv2 as cv
import math
import time
import argparse

def getFaceBox(net, frame, conf_threshold=0.7):
    frameOpencvDnn = frame.copy()
    frameHeight = frameOpencvDnn.shape[0]
    frameWidth = frameOpencvDnn.shape[1]
    blob = cv.dnn.blobFromImage(frameOpencvDnn, 1.0, (300, 300), [104,
117, 123], True, False)

net.setInput(blob)
detections = net.forward()
bboxes = []
for i in range(detections.shape[2]):
    confidence = detections[0, 0, i, 2]
    if confidence > conf_threshold:
        x1 = int(detections[0, 0, i, 4] * frameWidth)
        y1 = int(detections[0, 0, i, 4] * frameHeight)
        x2 = int(detections[0, 0, i, 5] * frameWidth)
        y2 = int(detections[0, 0, i, 6] * frameHeight)
        bboxes.append([x1, y1, x2, y2])
        cv.rectangle(frameOpencvDnn, (x1, y1), (x2, y2), (0, 255, 0),
int(round(frameHeight/150)), 8)
return frameOpencvDnn, bboxes

parser = argparse.ArgumentParser(description='Use this script to run age
and gender recognition using OpenCV.')
parser.add_argument('--input', help='Path to input image or video file.
Skip this argument to capture frames from a camera.')

args = parser.parse_args()

faceProto = "opencv_face_detector.pbtxt"
faceModel = "opencv_face_detector_uint8.pb"

ageProto = "age_deploy.prototxt"
ageModel = "age_net.caffemodel"

genderProto = "gender_deploy.prototxt"
genderModel = "gender_net.caffemodel"

MODEL_MEAN_VALUES = (78.4263377603, 87.7689143744, 114.895847746)
ageList = ['(0-2)', '(4-6)', '(8-12)', '(15-20)', '(25-32)', '(38-43)', '(48-53)', '(60-100)']
genderList = ['Male', 'Female']

ageNet = cv.dnn.readNet(ageModel, ageProto)
genderNet = cv.dnn.readNet(genderModel, genderProto)
faceNet = cv.dnn.readNet(faceModel, faceProto)

cap = cv.VideoCapture(args.input if args.input else 0)
padding = 20
while cv.waitKey(1) < 0:
# Read frame
t = time.time()
hasFrame, frame = cap.read()
if not hasFrame:
    cv.waitKey()
    break

frameFace, bboxes = getFaceBox(faceNet, frame)
if not bboxes:
    print("No face Detected, Checking next frame")
    continue

for bbox in bboxes:
    # print(bbox)
    face = frame[max(0,bbox[1]-
padding):min(bbox[3]+padding,frame.shape[0]-1),max(0,bbox[0]-
padding):min(bbox[2]+padding, frame.shape[1]-1)]

    blob = cv.dnn.blobFromImage(face, 1.0, (227, 227), MODEL_MEAN_VALUES,
swapRB=False)
    genderNet.setInput(blob)
    genderPreds = genderNet.forward()
    gender = genderList[genderPreds[0].argmax()]
    # print("Gender Output : {}".format(genderPreds))
    print("Gender : {}, conf = {:.3f}".format(gender,
genderPreds[0].max()))

    ageNet.setInput(blob)
</code>```

So to the point can someone tell me how to fix this? please

```<code>Traceback (most recent call last):
  File ".\AgeGender.py", line 47, in <module>
    ageNet = cv.dnn.readNet(ageModel, ageProto)
cv2.error: OpenCV(4.1.0) C:\projects\opencv-
python\opencv\modules\dnn\src\caffe\caffe_io.cpp:1132: error:
(-2:Unspecified error) FAILED: fs.is_open(). Can't open
"age_net.caffemodel" in function 'cv::dnn::ReadProtoFromBinaryFile'
</code>```

I just want to script to run normally without any errors so I could finish this nightmare

答:
It turns out that server was overloaded so downloaded files were not compleated.
After I downloaded "FULL" package everything began to work. I was missing literally 1 MB of 1 file that unfortunately was crucial for the whole script to work properly.

Thank you for help and sorry for a problem.

Body:
Ok. I have got a "simple" homework from my teacher. Homework was about just changing lanes of command from python.exe .\AgeGender.py --input .\sample.jpg to python.exe .\AgeGender.py --input .\test.jpg

Link to files library: https://drive.google.com/file/d/1gvIhxmFPvEcbDcPoyjnkcjuxNiiXD1FY/view?usp=sharing

From the beging. Teacher said that all what I have to do is any terminal to run this. Well it turns out I had to learn how to run scripts from cmd after 2 hours of fighting and trying to run this AgeGender.py. Of course at the begginig there was no way to run python.exe from windows command promt so I had to find a way to put all files in to pycharm scripts folder ONLY to find out that script is wrongly written and that I have to find a way to fix it...

import cv2 as cv
import math
import time
import argparse

def getFaceBox(net, frame, conf_threshold=0.7):
    frameOpencvDnn = frame.copy()
    frameHeight = frameOpencvDnn.shape[0]
    frameWidth = frameOpencvDnn.shape[1]
    blob = cv.dnn.blobFromImage(frameOpencvDnn, 1.0, (300, 300), [104,
117, 123], True, False)

net.setInput(blob)
detections = net.forward()
bboxes = []
for i in range(detections.shape[2]):
    confidence = detections[0, 0, i, 2]
    if confidence > conf_threshold:
        x1 = int(detections[0, 0, i, 4] * frameWidth)
        y1 = int(detections[0, 0, i, 4] * frameHeight)
        x2 = int(detections[0, 0, i, 5] * frameWidth)
        y2 = int(detections[0, 0, i, 6] * frameHeight)
        bboxes.append([x1, y1, x2, y2])
        cv.rectangle(frameOpencvDnn, (x1, y1), (x2, y2), (0, 255, 0),
int(round(frameHeight/150)), 8)
return frameOpencvDnn, bboxes

parser = argparse.ArgumentParser(description='Use this script to run age
and gender recognition using OpenCV.')
parser.add_argument('--input', help='Path to input image or video file.
Skip this argument to capture frames from a camera.')

args = parser.parse_args()

faceProto = "opencv_face_detector.pbtxt"
faceModel = "opencv_face_detector_uint8.pb"

ageProto = "age_deploy.prototxt"
ageModel = "age_net.caffemodel"

genderProto = "gender_deploy.prototxt"
genderModel = "gender_net.caffemodel"

MODEL_MEAN_VALUES = (78.4263377603, 87.7689143744, 114.895847746)
ageList = ['(0-2)', '(4-6)', '(8-12)', '(15-20)', '(25-32)', '(38-43)', '(48-53)', '(60-100)']
genderList = ['Male', 'Female']

ageNet = cv.dnn.readNet(ageModel, ageProto)
genderNet = cv.dnn.readNet(genderModel, genderProto)
faceNet = cv.dnn.readNet(faceModel, faceProto)

cap = cv.VideoCapture(args.input if args.input else 0)
padding = 20
while cv.waitKey(1) < 0:
# Read frame
t = time.time()
hasFrame, frame = cap.read()
if not hasFrame:
    cv.waitKey()
    break

frameFace, bboxes = getFaceBox(faceNet, frame)
if not bboxes:
    print("No face Detected, Checking next frame")
    continue

for bbox in bboxes:
    # print(bbox)
    face = frame[max(0,bbox[1]-
padding):min(bbox[3]+padding,frame.shape[0]-1),max(0,bbox[0]-
padding):min(bbox[2]+padding, frame.shape[1]-1)]

    blob = cv.dnn.blobFromImage(face, 1.0, (227, 227), MODEL_MEAN_VALUES,
swapRB=False)
    genderNet.setInput(blob)
    genderPreds = genderNet.forward()
    gender = genderList[genderPreds[0].argmax()]
    # print("Gender Output : {}".format(genderPreds))
    print("Gender : {}, conf = {:.3f}".format(gender,
genderPreds[0].max()))

    ageNet.setInput(blob)

So to the point can someone tell me how to fix this? please

Traceback (most recent call last):
  File ".\AgeGender.py", line 47, in <module>
    ageNet = cv.dnn.readNet(ageModel, ageProto)
cv2.error: OpenCV(4.1.0) C:\projects\opencv-
python\opencv\modules\dnn\src\caffe\caffe_io.cpp:1132: error:
(-2:Unspecified error) FAILED: fs.is_open(). Can't open
"age_net.caffemodel" in function 'cv::dnn::ReadProtoFromBinaryFile'

I just want to script to run normally without any errors so I could finish this nightmare


问:
Is there a JavaScript (or jQuery) shortcut for "function(){return false;}"?
To prevent actions from happening, I frequently type

```<code>function(){return false;}
</code>```

Is there a shortcut?

答:
Do you really think that's too much typing?

Why not have a global variable named f set to false, and use function() {return f;}

OwnerDisplayName: Steven Noble

Body:
To prevent actions from happening, I frequently type

function(){return false;}

Is there a shortcut?

ContentLicense: CC BY-SA 2.5


问:
Data populated wrongly in DataGridView
I have a DataGridView that is populated using a list.
During Runtime, the user can filter the data by entering data in a textbox. I am able to do the filtering part.

But the problem i am facing is when i change the datasource to the new datasource in the Textbox1_TextChanged event, the datagridview is populating the data with rows equal to the number of rows in my new datasource but each row is replica of the first row.

When I check the DataSource of the datagridview it has the data of the new DataSource.

So when I check the row selected in the datagridview_doubleclick event, the DataBoundItem gives me the exact object that it should give according the to new datasource.

What might have gone wrong??

答:
Maybe I am wrong, but do you need to clear the DataGridView when binding to a new datasource.... my binding skills are lacking....

Try clearing the DataGridView, before changing the datasource like :

```<code>DataGridView.Rows.Clear();
</code>```

Title: Data populated wrongly in DataGridView

Body:
Maybe I am wrong, but do you need to clear the DataGridView when binding to a new datasource.... my binding skills are lacking....

Try clearing the DataGridView, before changing the datasource like :

DataGridView.Rows.Clear();


问:
How can I get OmniSharp VSCode intellisense to work with WSL-compiled code?
When I run dotnet build on my code from my WSL (Windows Subsystem for Linux) distro, C# intellisense breaks and I get errors like the following:

I've managed to set up the launch configurations found here, but that doesn't help with Intellisense, unless I've missed something.

I presume it has something to do with path configurations, but I'm not sure what to change, or where I should change it.

In short, how can I compile and run my code on WSL and edit it in VS Code without errors or warnings?

答:
As I fell into this question when I looked for this problem I decided to go back to show how I managed to solve it.

To OmniSharp work with WSL i installed the Insiders version of VS Code and the extension Remote - WSL.
Done.

Links:

https://code.visualstudio.com/insiders/

https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-wsl

OBS: You have to install on your WSL Linux distro the wget and msbuild


问:
Test each case/return using Jest/ Enzyme
Trying to test the following using jest and Enzyme. When I run npm-coverage, it shows that each case has not being tested. Not really sure how to approach a solution

Here is the code

```<code>renderColumnDropdown = () => {
if (this.props.columnIdList != undefined) {
let columnOptions = Object.keys(this.props.columnIdList).map(key => {
  switch (key) {
    case 'sort':
      return false
    case 'filters':
      return false
    case 'group':
      return false
    case 'dimensions':
      return false
    case 'pivot':
      return false
    case 'pivotanalysis':
      return false
    default:
    return (
      <option value={key} key={key}>{this.props.columnIdList[key]}</option>
    )
  }
})
</code>```

This is how I usually set up my test cases: Using shallow

```<code>it('Test renderColumnDropdown function',() => {
  wrapper.setProps({
    columnIdList:[{
        key:'pivotanalysis'
        }],
    })
  wrapper.setState({
     }),
  wrapper.update();
  expect(wrapper.instance().renderColumnDropdown({defaultData:{filters:[{ column:''}]}})).toBeDefined();
});
</code>```

答:
You can refactor your code by combining all cases in one which are returning same value to get them covered, and it should have first key to cover all branches.</p>

```<code>switch (key) {
    case 'sort':
    case 'filters':
    case 'group':
    case 'dimensions':
    case 'pivot':
    case 'pivotanalysis':
        return false
    default:
        return (
            <option value={key} key={key}>{this.props.columnIdList[key]}</option>
        )
</code>```

Body:
Trying to test the following using jest and Enzyme. When I run npm-coverage, it shows that each case has not being tested. Not really sure how to approach a solution

Here is the code

renderColumnDropdown = () => {
if (this.props.columnIdList != undefined) {
let columnOptions = Object.keys(this.props.columnIdList).map(key => {
  switch (key) {
    case 'sort':
      return false
    case 'filters':
      return false
    case 'group':
      return false
    case 'dimensions':
      return false
    case 'pivot':
      return false
    case 'pivotanalysis':
      return false
    default:
    return (
      <option value={key} key={key}>{this.props.columnIdList[key]}</option>
    )
  }
})

This is how I usually set up my test cases: Using shallow

it('Test renderColumnDropdown function',() => {
  wrapper.setProps({
    columnIdList:[{
        key:'pivotanalysis'
        }],
    })
  wrapper.setState({
     }),
  wrapper.update();
  expect(wrapper.instance().renderColumnDropdown({defaultData:{filters:[{ column:''}]}})).toBeDefined();
});

Body:
You can refactor your code by combining all cases in one which are returning same value to get them covered, and it should have first key to cover all branches.

switch (key) {
    case 'sort':
    case 'filters':
    case 'group':
    case 'dimensions':
    case 'pivot':
    case 'pivotanalysis':
        return false
    default:
        return (
            <option value={key} key={key}>{this.props.columnIdList[key]}</option>
        )


问:
Implementing IN /LIKE in MDX
I have a dimension called [Band] and it can have several different values:

```<code>[Band].&[A]&[Under $400]
[Band].&[B]&[$400 - $1,000]
[Band].&[C]&[$1,000 - $2,500]
[Band].&[D]&[$2,500 - $3,500]
...
</code>```

I'm trying to write a query where I can cut by a sublist of these values.

Here's the query that is not working because the .isin function doesn't exist in MDX, but you'll see what I'm trying to do:

```<code>SELECT
  NON EMPTY {[Measure A], [Measure B]} ON COLUMNS,
  NON EMPTY {([Band].isin(['Under $400', '$400 - $1,000']).ALLMEMBERS)} --fail on .isin(
  DIMENSION PROPERTIES MEMBER_CAPTION ON ROWS
FROM (
  SELECT
    ({[Foo].&[Bar]}) ON COLUMNS
  FROM
    [CUBE]
)
</code>```

Now, here's a query that is working, but it only gives me one [Band] value:

```<code>SELECT
  NON EMPTY {[Measure A], [Measure B]} ON COLUMNS,
  NON EMPTY {([Band].&[A]&[Under $400])}
  DIMENSION PROPERTIES MEMBER_CAPTION ON ROWS
FROM (
  SELECT
    ({[Foo].&[Bar]}) ON COLUMNS
  FROM
    [CUBE]
)
</code>```

This returns a valid result of:

```<code>              Measure A    Measure B
Under $400    1795.67%     58.48%
</code>```

But I'd like to see results where it returns the aggregated values of multiple [Band] dimension values. How can this be done in MDX?

As you can probably tell I've never used MDX before, but as I search on this issue I see things like taking the intersect, or using ChildrenSet. But it doesn't seem very intuitive.

Can you point me in the right direction?

答:
figured it out I think</p>

```<code>SELECT
  NON EMPTY {[Measure A], [Measure B]} ON COLUMNS,
  NON EMPTY {[Band].[Under $400], [Band].[$1,000 - $2,500]}
  DIMENSION PROPERTIES MEMBER_CAPTION ON ROWS
FROM (
  SELECT
    ({[Foo].&[Bar]}) ON COLUMNS
  FROM
    [CUBE]
)
</code>```

Title: Implementing IN /LIKE in MDX

Body:
I have a dimension called [Band] and it can have several different values:

[Band].&[A]&[Under $400]
[Band].&[B]&[$400 - $1,000]
[Band].&[C]&[$1,000 - $2,500]
[Band].&[D]&[$2,500 - $3,500]
...

I'm trying to write a query where I can cut by a sublist of these values.

Here's the query that is not working because the .isin function doesn't exist in MDX, but you'll see what I'm trying to do:

SELECT
  NON EMPTY {[Measure A], [Measure B]} ON COLUMNS,
  NON EMPTY {([Band].isin(['Under $400', '$400 - $1,000']).ALLMEMBERS)} --fail on .isin(
  DIMENSION PROPERTIES MEMBER_CAPTION ON ROWS
FROM (
  SELECT
    ({[Foo].&[Bar]}) ON COLUMNS
  FROM
    [CUBE]
)

Now, here's a query that is working, but it only gives me one [Band] value:

SELECT
  NON EMPTY {[Measure A], [Measure B]} ON COLUMNS,
  NON EMPTY {([Band].&[A]&[Under $400])}
  DIMENSION PROPERTIES MEMBER_CAPTION ON ROWS
FROM (
  SELECT
    ({[Foo].&[Bar]}) ON COLUMNS
  FROM
    [CUBE]
)

This returns a valid result of:

              Measure A    Measure B
Under $400    1795.67%     58.48%

But I'd like to see results where it returns the aggregated values of multiple [Band] dimension values. How can this be done in MDX?

As you can probably tell I've never used MDX before, but as I search on this issue I see things like taking the intersect, or using ChildrenSet. But it doesn't seem very intuitive.

Can you point me in the right direction?

Body:
figured it out I think

SELECT
  NON EMPTY {[Measure A], [Measure B]} ON COLUMNS,
  NON EMPTY {[Band].[Under $400], [Band].[$1,000 - $2,500]}
  DIMENSION PROPERTIES MEMBER_CAPTION ON ROWS
FROM (
  SELECT
    ({[Foo].&[Bar]}) ON COLUMNS
  FROM
    [CUBE]
)


问:
How to fix Native Host Has Exited error in Chrome browser extension -- Native Messaging
How to fix a "Native host has exited" error in my Chrome browser extension for Mac?  The docs here on Native Messaging specifically mention this error towards the bottom, and suggest a likely cause, but it is stated quite generally ("This is most likely initiated from your native messaging host") and it's unclear what to attempt to do to solve this.

The logging output in Terminal (if you launch Chrome from the Mac Terminal you can view logging info) has led me to believe that the process for the native host app is itself is never successfully started.  I keep getting:

```<code>LaunchProcess: failed to execvp:
/Users/mycomputer1/Documents/myhost.app
</code>```

However, the actual code that prints "Native host has exited" to the console for the background javascript page is:

```<code>function onDisconnected() {
  console.log("Inside onDisconnected(): " + chrome.runtime.lastError.message);
  port = null;
}
</code>```

The onDisconnected() listener is actually invoked as a result of calling connectNative(), which I've done here according to the documentation:

```<code>chrome.runtime.onMessageExternal.addListener(
function(request, sender, sendResponse) {
//var imgdata = JSON.stringify(request.imgdata);
//process it somehow here

    port = chrome.runtime.connectNative("com.allinlearning.ailhost");

    if (port)
    {
       console.log("connectNative() returned a non-null port");
    }
});
</code>```

I know that connectNative() succeeds at some level bc it returns a valid port. However, connectNative() goes on to attempt to locate the native host app and try to launch it.  The docs suggests that the host app is the culprit, somehow initiating the breaking of a "pipe" between Chrome and the native app, although my host app has implemented no communication with stdout or stdin at all.  Besides, the Chrome log msg ("LaunchProcess: failed to execvp:") seems to indicate that my Mac app was never even launched successfully.

There's more: some source code I found online (perhaps dated? source file) reveals exactly where this "Native host has exited" msg originates, and an examination suggests why Google Chrome's code is closing things down. In HandleReadResult() a Close() is called supplying the very msg and then closes things in response to a Posix read() returning 0. But what in the wide, wide world of sports am I doing wrong (or not doing at all) in my Mac app to cause this the read to fail? My Mac app is not writing anything to stdout, so how is not-writing-anything causing the read error? Or is all of this misleading me, and execvp's failure to launch my host app the deeper cause?  If so, why?  It's a plain-jane, barebones Mac app.

答:
Your native app and chrome communicate through the console, which in most cases is hidden. If your app uses the console for something more than communicating with chrome (e.g. executing a system command) chrome WILL catch that and interpret it as a bad response from your app and close the connection between them.

So you are advised to use one of the following workarounds:

Don't use the (same) console for running anything other than your communication with chrome

Buffer your console output instead of sending it to stdout

One more thing to notice is that in some languages (e.g. php) some commands (e.g. preg_match) seem to don't have any output as they manipulate data based on their arguments, BUT they do return a result (e.g. true/false) and if you don't suppress that result (@function() in php) or save it to a variable then it goes to stdout and causes chrome to disconnect.

Sorry if not directly relevant to the question but I hope this helps some people as this question shows way up on the search results. Myself, I struggled with such a problem for a good sum of hours.

Body:
How to fix a "Native host has exited" error in my Chrome browser extension for Mac?  The docs here on Native Messaging specifically mention this error towards the bottom, and suggest a likely cause, but it is stated quite generally ("This is most likely initiated from your native messaging host") and it's unclear what to attempt to do to solve this.

The logging output in Terminal (if you launch Chrome from the Mac Terminal you can view logging info) has led me to believe that the process for the native host app is itself is never successfully started.  I keep getting:

LaunchProcess: failed to execvp:
/Users/mycomputer1/Documents/myhost.app

However, the actual code that prints "Native host has exited" to the console for the background javascript page is:

function onDisconnected() {
  console.log("Inside onDisconnected(): " + chrome.runtime.lastError.message);
  port = null;
}

The onDisconnected() listener is actually invoked as a result of calling connectNative(), which I've done here according to the documentation:

chrome.runtime.onMessageExternal.addListener(
function(request, sender, sendResponse) {
//var imgdata = JSON.stringify(request.imgdata);
//process it somehow here

    port = chrome.runtime.connectNative("com.allinlearning.ailhost");

    if (port)
    {
       console.log("connectNative() returned a non-null port");
    }
});

I know that connectNative() succeeds at some level bc it returns a valid port. However, connectNative() goes on to attempt to locate the native host app and try to launch it.  The docs suggests that the host app is the culprit, somehow initiating the breaking of a "pipe" between Chrome and the native app, although my host app has implemented no communication with stdout or stdin at all.  Besides, the Chrome log msg ("LaunchProcess: failed to execvp:") seems to indicate that my Mac app was never even launched successfully.

There's more: some source code I found online (perhaps dated? source file) reveals exactly where this "Native host has exited" msg originates, and an examination suggests why Google Chrome's code is closing things down. In HandleReadResult() a Close() is called supplying the very msg and then closes things in response to a Posix read() returning 0. But what in the wide, wide world of sports am I doing wrong (or not doing at all) in my Mac app to cause this the read to fail? My Mac app is not writing anything to stdout, so how is not-writing-anything causing the read error? Or is all of this misleading me, and execvp's failure to launch my host app the deeper cause?  If so, why?  It's a plain-jane, barebones Mac app.


问:
Why does typescript think my property could be void after I throw in a promise catch block?
```<code>async function fetchMpdData(mpdUrl: string): Promise<MPDFileContainer> {
  const data = await fetch(mpdUrl)
    .then((response): Promise<string> => response.text())
    .catch(
      (error): void => {
        throw new FetchError(`Error fetching file ${mpdUrl}: ${error}`);
      },
    );
  return parseStringMpd(data);
}
</code>```

parseStringMpd takes a string.  The data passed to parseStringMpd is failing with:

Argument of type 'string | void' is not assignable to parameter of type 'string'.

There are a few other questions on SO that talk about how if the promise fails the catch block will cause the data property to be void.  But in my case the catch block is throwing an error.  So the data that is being complained about will never be reached.

Is the typescript parser just not able to handle this?

答:
Your error is here:

```<code>  (error): void => {
    throw new FetchError(`Error fetching file ${mpdUrl}: ${error}`);
  },
</code>```

You declare that the return type is void (a function that returns nothing) instead of never (a function that never returns). You could change it to : never but I suggest you to let TypeScript infer it:

```<code>  error => {
    throw new FetchError(`Error fetching file ${mpdUrl}: ${error}`);
  },
</code>```

… But if you use async / await you could rewrite your code with them:

```<code>async function fetchMpdData(mpdUrl: string): Promise<MPDFileContainer> {
    try {
        const response = await fetch(mpdUrl)
        const data = await response.text()
        return parseStringMpd(data);
    } catch (error) {
        throw new Error(`Error fetching file ${mpdUrl}: ${error}`)
    }
}
</code>```

Notice that variables response and data are correctly typed by inference. It's useless to declare their types.

Body:
async function fetchMpdData(mpdUrl: string): Promise<MPDFileContainer> {
  const data = await fetch(mpdUrl)
    .then((response): Promise<string> => response.text())
    .catch(
      (error): void => {
        throw new FetchError(`Error fetching file ${mpdUrl}: ${error}`);
      },
    );
  return parseStringMpd(data);
}

parseStringMpd takes a string.  The data passed to parseStringMpd is failing with:

Argument of type 'string | void' is not assignable to parameter of type 'string'.

There are a few other questions on SO that talk about how if the promise fails the catch block will cause the data property to be void.  But in my case the catch block is throwing an error.  So the data that is being complained about will never be reached.

Is the typescript parser just not able to handle this?

Body:
Your error is here:

  (error): void => {
    throw new FetchError(`Error fetching file ${mpdUrl}: ${error}`);
  },

You declare that the return type is void (a function that returns nothing) instead of never (a function that never returns). You could change it to : never but I suggest you to let TypeScript infer it:

  error => {
    throw new FetchError(`Error fetching file ${mpdUrl}: ${error}`);
  },

… But if you use async / await you could rewrite your code with them:

async function fetchMpdData(mpdUrl: string): Promise<MPDFileContainer> {
    try {
        const response = await fetch(mpdUrl)
        const data = await response.text()
        return parseStringMpd(data);
    } catch (error) {
        throw new Error(`Error fetching file ${mpdUrl}: ${error}`)
    }
}

Notice that variables response and data are correctly typed by inference. It's useless to declare their types.


问:
How to send POST request containing array of object to PHP server from c# windows application?
I'm developing a C# application that reads local MySQL database, and send the data as POST request to online PHP server.

The PHP server is ready to receive data like this. (It is from Postman x-www-form-url-encoded)

```<code>token:da979d2922c74d7851e6f0eff2270d73
branch:JKT
items[0][code]:0001-W*XL*B
items[0][name]:018/17 DRS XL BLUE
items[0][stock]:0
items[1][code]:0001-W*XL*BK
items[1][name]:018/17 DRS XL BLACK
items[1][stock]:0
</code>```

This is my c# code. I can't add array of objects to dictionary, so I'm looking for other way around.

```<code>string query = "SELECT * FROM items";
db.Connection.Open();

MySqlDataAdapter dataAdapter = new MySqlDataAdapter(query, db.Connection);
DataTable dataTable = new DataTable();
dataAdapter.Fill(dataTable);

db.Connection.Close();

var dictionary = new Dictionary<string, string>();

dictionary.Add("token", "da979d2922c74d7851e6f0eff2270d73");
dictionary.Add("branch", "JKT");
dictionary.Add("items", dataTable); // Argument 2: cannot convert from 'System.Data.DataTable' to 'string'

var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, "https://mysite.test/sync")
{
    Content = new FormUrlEncodedContent(dictionary)
};
var response = await client.SendAsync(request);
string responseString = await response.Content.ReadAsStringAsync();
</code>```

Is there other way to send POST request form data aside from Dictionary?

答: My answer may be not one that you want, but if u pass strings u can concatenate them in c# with ; separator and do explode string ; on php and get array. Also try: dictionary.Add("items[]", dataTable); </p>

Body:
I'm developing a C# application that reads local MySQL database, and send the data as POST request to online PHP server.

The PHP server is ready to receive data like this. (It is from Postman x-www-form-url-encoded)

token:da979d2922c74d7851e6f0eff2270d73
branch:JKT
items[0][code]:0001-W*XL*B
items[0][name]:018/17 DRS XL BLUE
items[0][stock]:0
items[1][code]:0001-W*XL*BK
items[1][name]:018/17 DRS XL BLACK
items[1][stock]:0

This is my c# code. I can't add array of objects to dictionary, so I'm looking for other way around.

string query = "SELECT * FROM items";
db.Connection.Open();

MySqlDataAdapter dataAdapter = new MySqlDataAdapter(query, db.Connection);
DataTable dataTable = new DataTable();
dataAdapter.Fill(dataTable);

db.Connection.Close();

var dictionary = new Dictionary<string, string>();

dictionary.Add("token", "da979d2922c74d7851e6f0eff2270d73");
dictionary.Add("branch", "JKT");
dictionary.Add("items", dataTable); // Argument 2: cannot convert from 'System.Data.DataTable' to 'string'

var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, "https://mysite.test/sync")
{
    Content = new FormUrlEncodedContent(dictionary)
};
var response = await client.SendAsync(request);
string responseString = await response.Content.ReadAsStringAsync();

Is there other way to send POST request form data aside from Dictionary?


问:
installation of package ‘car’ had non-zero exit status in R 3.6.0
I try to install car package in Windows version of R 3.6.0. I use Windows 8.1. I got following error message: installation of package ‘car’ had non-zero exit status

Full output:

```<code>> install.packages("car")
Installing package into ‘C:/Users/Zsófia/Documents/R/win-library/3.6’
(as ‘lib’ is unspecified)
--- Please select a CRAN mirror for use in this session ---

  There is a binary version available but the source version is later:
    binary source needs_compilation
car  3.0-2  3.0-3             FALSE

installing the source package ‘car’

trying URL 'https://cloud.r-project.org/src/contrib/car_3.0-3.tar.gz'
Content type 'application/x-gzip' length 539020 bytes (526 KB)
downloaded 526 KB

* installing *source* package 'car' ...
** package 'car' successfully unpacked and MD5 sums checked
** using staged installation
Warning in file(file, if (append) "a" else "w") :
  cannot open file 'C:/Users/Zssfia/Documents/R/win-library/3.6/00LOCK-car/00new/car/DESCRIPTION': No such file or directory
Error in file(file, if (append) "a" else "w") :
  cannot open the connection
ERROR: installing package DESCRIPTION failed for package 'car'
* removing 'C:/Users/Zsófia/Documents/R/win-library/3.6/car'

The downloaded source packages are in
        ‘C:\Users\Zsófia\AppData\Local\Temp\RtmpK0Qk4Q\downloaded_packages’
Warning message:
In install.packages("car") :
  installation of package ‘car’ had non-zero exit status
</code>```

Other packages, like psych are successfully installed.

答:
For windows, try version 3.0.2 of the car package.</p>

```<code>install.packages("https://cran.r-project.org/bin/windows/contrib/3.5/car_3.0-2.zip",
                 lib = .libPaths()[1], repos = NULL, type = "win.binary")
packageVersion("car")

package ‘car’ successfully unpacked and MD5 sums checked
> packageVersion("car")
[1] ‘3.0.2’
</code>```

Body:
I try to install car package in Windows version of R 3.6.0. I use Windows 8.1. I got following error message: installation of package ‘car’ had non-zero exit status

Full output:

> install.packages("car")
Installing package into ‘C:/Users/Zsófia/Documents/R/win-library/3.6’
(as ‘lib’ is unspecified)
--- Please select a CRAN mirror for use in this session ---

  There is a binary version available but the source version is later:
    binary source needs_compilation
car  3.0-2  3.0-3             FALSE

installing the source package ‘car’

trying URL 'https://cloud.r-project.org/src/contrib/car_3.0-3.tar.gz'
Content type 'application/x-gzip' length 539020 bytes (526 KB)
downloaded 526 KB

* installing *source* package 'car' ...
** package 'car' successfully unpacked and MD5 sums checked
** using staged installation
Warning in file(file, if (append) "a" else "w") :
  cannot open file 'C:/Users/Zssfia/Documents/R/win-library/3.6/00LOCK-car/00new/car/DESCRIPTION': No such file or directory
Error in file(file, if (append) "a" else "w") :
  cannot open the connection
ERROR: installing package DESCRIPTION failed for package 'car'
* removing 'C:/Users/Zsófia/Documents/R/win-library/3.6/car'

The downloaded source packages are in
        ‘C:\Users\Zsófia\AppData\Local\Temp\RtmpK0Qk4Q\downloaded_packages’
Warning message:
In install.packages("car") :
  installation of package ‘car’ had non-zero exit status

Other packages, like psych are successfully installed.

Body:
For windows, try version 3.0.2 of the car package.

install.packages("https://cran.r-project.org/bin/windows/contrib/3.5/car_3.0-2.zip",
                 lib = .libPaths()[1], repos = NULL, type = "win.binary")
packageVersion("car")

package ‘car’ successfully unpacked and MD5 sums checked
> packageVersion("car")
[1] ‘3.0.2’


问:
Confused about install -m and install -d using Yocto
I have taken over a Yocto project, and inside a .bb recipe file, I see the following lines to install new directories in the image:

    do_install() {
    install -m 0755 -d ${DEPLOY_DIR_IMAGE}/app
    install -m 0755 -d ${DEPLOY_DIR_IMAGE}/app/apiary
    install -m 0755 -d ${DEPLOY_DIR_IMAGE}/app/lib
    install -m 0755 -d ${DEPLOY_DIR_IMAGE}/app/config
    install -m 0755 -d ${DEPLOY_DIR_IMAGE}/app/scripts
    install -m 0755 -d ${DEPLOY_DIR_IMAGE}/app/keys
```

This works but I am confused. From my reading about Yocto and doing do_install, I thought that the -m option is only for installing files and not directories.

What is the effect of doing install -m 0755 -d, both the -m and -d options with the install command?

Also, why is there no ${D} variable like in the majority of other directory installations which I see?

I normally wouldn't resort to Stack Overflow for a question like this, but there is so much inconsistency that I don't understand, and hard to find an answer.

答:
The task in question is defined as a shell function.  The install command used within is a shell command, not anything Yocto- or BitBake-specific, so you should be looking at its docs for enlightenment, not relying on BitBake documentation or examples.  In the context of Yocto in particular, however, you should be looking at the documentation for the GNU coreutils version of the install program (as linked above), which is the one you will invariably find on Linux systems.*

From my reading about Yocto and doing do_install, I thought that the -m option is only for installing files and not directories.

I'm not sure what would make you think that, other than just not seeing it applied to directories before.

What is the effect of doing install -m 0755 -d, both the -m and -d options with the install command?

The -m option sets the mode (access-control bits) of the installed object(s).  Directories have modes just like regular files do, and the -m option has the same meaning for installing directories as it does for installing regular files.

The -d option specifies that the names specified for installation are to be taken as directories to be created, along with any missing directories in the specified path.  As @jww observed in comments, the effect is analogous to that of mkdir -p.

These options are orthogonal.  When used together, their effects combine in the natural way: the specified directories are created, with parent directories if needed, and all directories created are assigned the specified mode.  Setting the modes explicitly to 0755 is superfluous, however, because that's the default.  That may be why you are not used to seeing -m options used for directories.

Also, why is there no ${D} variable like in the majority of other directory installations which I see?

The Yocto specifications for do_install say that it should install files relative to ${D}, whereas the variable DEPLOY_DIR_IMAGE refers to the location for ready-to-install images.  It seems like installing to ${DEPLOY_DIR_IMAGE} would be the wrong thing to do, but that doesn't necessarily mean that it wouldn't produce the desired ultimate effect.  Or perhaps the recipe was simply written for some older version of BitBake where it made more sense.  In any event, sorting out the the details would be a much deeper and more involved analysis than I am prepared to perform for you.

*install is not standardized by POSIX.  The GNU version was inspired by BSD's program of the same name, and current versions of that have similar options and behavior, including specifically with respect to the -m and -d options.

Body:
I have taken over a Yocto project, and inside a .bb recipe file, I see the following lines to install new directories in the image:

    do_install() {
    install -m 0755 -d ${DEPLOY_DIR_IMAGE}/app
    install -m 0755 -d ${DEPLOY_DIR_IMAGE}/app/apiary
    install -m 0755 -d ${DEPLOY_DIR_IMAGE}/app/lib
    install -m 0755 -d ${DEPLOY_DIR_IMAGE}/app/config
    install -m 0755 -d ${DEPLOY_DIR_IMAGE}/app/scripts
    install -m 0755 -d ${DEPLOY_DIR_IMAGE}/app/keys

This works but I am confused. From my reading about Yocto and doing do_install, I thought that the -m option is only for installing files and not directories.

What is the effect of doing install -m 0755 -d, both the -m and -d options with the install command?

Also, why is there no ${D} variable like in the majority of other directory installations which I see?

I normally wouldn't resort to Stack Overflow for a question like this, but there is so much inconsistency that I don't understand, and hard to find an answer.


问:
Win forms, how to assign a method to radio button when checked
I am new to c# and Win forms so please be patient with me.

I have e radio buttons that has been written programatically. I want to update the value of which button is checked. Here is the code for one of the buttons

```<code>        RadioButton cab = new RadioButton();
        cab.Text = m_appContext.L10nManager.TranslateString("Modern");
        cab.Name = "Modern";
        cab.Location = new Point(15, 45);
        cab.AutoSize = true;
</code>```

I want to assign a "method" when it is checked. So I go ahead add this to my radio button:

```<code>ca.Checked = m_appContext.EWSMode;
</code>```

Here is the code for EWSMode:

```<code>    public enum EWSMode { Auto = 0, EWS = 1, Classical = 2 };
    EWSMode m_EWSMode = EWSMode.Auto;
    public EWSMode EWSMode
    {
        get { return m_EWSMode; }
        set { m_EWSMode = value; }
    }
</code>```

Depending on which radio button is selected I want to set m_EWSMode to that value. So by default

```<code>EWSMode m_EWSMode = EWSMode.Auto;
</code>```

When, say radio button EWS is selected I want to set m_EWSMode to EWS

At what point do I set/pass the new value to my EWSMode enum and how do I do it?

答:
You have to use an EventHandler, like this:

```<code>ca.Checked += new System.EventHandler(EWSMode);
</code>```

Note that EWSMode has to have the correct signature, taking object and EventArgs as parameters:

```<code>private void EWSMode(object sender, EventArgs e)
</code>```

If you want to set a variable's value according to what check is selected, you can subscribe them both to an event handler:

```<code>ca1.Checked += new System.EventHandler(EWSMode_Event);
ca2.Checked += new System.EventHandler(EWSMode_Event);
</code>```

And then put the logic in EWSMode_Event:

```<code>private void EWSMode_Event(object sender, EventArgs e)
{
//When ca1 or ca2 gets checked, this event will be triggered. Here, you would
//set your m_EWSMode variable.
}
</code>```

You can do the same thing using one event for each CheckBox:

```<code>ca1.Checked += new System.EventHandler(EWSMode_Event);

private void EWSMode_Event(object sender, EventArgs e)
{
    //When ca1 gets checked, this event will be triggered.

    EWSMode m_EWSMode = EWSMode.EWS;
}
</code>```

Body:
I am new to c# and Win forms so please be patient with me.

I have e radio buttons that has been written programatically. I want to update the value of which button is checked. Here is the code for one of the buttons

        RadioButton cab = new RadioButton();
        cab.Text = m_appContext.L10nManager.TranslateString("Modern");
        cab.Name = "Modern";
        cab.Location = new Point(15, 45);
        cab.AutoSize = true;

I want to assign a "method" when it is checked. So I go ahead add this to my radio button:

ca.Checked = m_appContext.EWSMode;

Here is the code for EWSMode:

    public enum EWSMode { Auto = 0, EWS = 1, Classical = 2 };
    EWSMode m_EWSMode = EWSMode.Auto;
    public EWSMode EWSMode
    {
        get { return m_EWSMode; }
        set { m_EWSMode = value; }
    }

Depending on which radio button is selected I want to set m_EWSMode to that value. So by default

EWSMode m_EWSMode = EWSMode.Auto;

When, say radio button EWS is selected I want to set m_EWSMode to EWS

At what point do I set/pass the new value to my EWSMode enum and how do I do it?

Body:
You have to use an EventHandler, like this:

ca.Checked += new System.EventHandler(EWSMode);

Note that EWSMode has to have the correct signature, taking object and EventArgs as parameters:

private void EWSMode(object sender, EventArgs e)

If you want to set a variable's value according to what check is selected, you can subscribe them both to an event handler:

ca1.Checked += new System.EventHandler(EWSMode_Event);
ca2.Checked += new System.EventHandler(EWSMode_Event);

And then put the logic in EWSMode_Event:

private void EWSMode_Event(object sender, EventArgs e)
{
//When ca1 or ca2 gets checked, this event will be triggered. Here, you would
//set your m_EWSMode variable.
}

You can do the same thing using one event for each CheckBox:

ca1.Checked += new System.EventHandler(EWSMode_Event);

private void EWSMode_Event(object sender, EventArgs e)
{
    //When ca1 gets checked, this event will be triggered.

    EWSMode m_EWSMode = EWSMode.EWS;
}


问:
Stopwords coming up in most influential words
I am running some NLP code, trying to find the most influential (positively or negatively) words in a survey. My problem is that, while I successfully add some extra stopwords to the NLTK stopwords file, they keep coming up as influential words later on.

So, I have a dataframe, first column contains scores, second column contains comments.

I add extra stopwords:

```<code>stopwords = stopwords.words('english')
extra = ['Cat', 'Dog']
stopwords.extend(extra)
</code>```

I check that they are added, using the len method before and after.

I create this function to remove punctuation and stopwords from my comments:

```<code>def text_process(comment):
   nopunc = [char for char in comment if char not in string.punctuation]
   nopunc = ''.join(nopunc)
   return [word for word in nopunc.split() if word.lower() not in stopwords]
</code>```

I run the model (not going to include the whole code since it doesn't make a difference):

```<code>corpus = df['Comment']
y = df['Label']
vectorizer = CountVectorizer(analyzer=text_process)
x = vectorizer.fit_transform(corpus)
</code>```

...

And then to get the most influential words:

```<code>feature_to_coef = {word: coef for word, coef in zip(vectorizer.get_feature_names(), nb.coef_[0])}

for best_positive in sorted(
    feature_to_coef.items(),
    key=lambda x: x[1],
    reverse=True)[:20]:
    print (best_positive)
</code>```

But, Cat and Dog are in the results.

What am I doing wrong, any ideas?

Thank you very much!

答:
Looks like it is because you have capitalize words 'Cat' and 'Dog'

In your text_process function, you have if word.lower() not in stopwords which only works if the stopwords are lower case

Body:
I am running some NLP code, trying to find the most influential (positively or negatively) words in a survey. My problem is that, while I successfully add some extra stopwords to the NLTK stopwords file, they keep coming up as influential words later on.

So, I have a dataframe, first column contains scores, second column contains comments.

I add extra stopwords:

stopwords = stopwords.words('english')
extra = ['Cat', 'Dog']
stopwords.extend(extra)

I check that they are added, using the len method before and after.

I create this function to remove punctuation and stopwords from my comments:

def text_process(comment):
   nopunc = [char for char in comment if char not in string.punctuation]
   nopunc = ''.join(nopunc)
   return [word for word in nopunc.split() if word.lower() not in stopwords]

I run the model (not going to include the whole code since it doesn't make a difference):

corpus = df['Comment']
y = df['Label']
vectorizer = CountVectorizer(analyzer=text_process)
x = vectorizer.fit_transform(corpus)

...

And then to get the most influential words:

feature_to_coef = {word: coef for word, coef in zip(vectorizer.get_feature_names(), nb.coef_[0])}

for best_positive in sorted(
    feature_to_coef.items(),
    key=lambda x: x[1],
    reverse=True)[:20]:
    print (best_positive)

But, Cat and Dog are in the results.

What am I doing wrong, any ideas?

Thank you very much!


问:
How to get php vars to display in html
I am executing a php script which collects some variables from a form, then displays a page from a MySQL table. The page is displayed fine, but the echoed variable are not.

```<code>    <h4>Conference Registration</h4>
    <p><strong>
        <?php echo $confName $confDate; ?>
    </strong></p>
</code>```

The expected result is that the two variable are displayed.
I tested that the variable were available by inserting an echo command at the top of the page.

The actual result is that the variable are not displayed.

When displaying the page source in the browser and hovering over the <?php line displayed in red, the following is displayed:

Saw "<p". Probable cause: Attempt to use an XML processing
  instruction in HTML. (XML procesing instructions are not supported in
  HTML.)

答:
echo takes in a string or a list of strings PHP Manual

echo can accept

($confName, $confDate) (handles as a list)

$confName, $confDate (handles as a list)

$confName . $confDate (handles as a single string since it is concatenated)

so something like

```<code><h4>Conference Registration</h4>
  <p><strong>
    <?php echo $confName, $confDate; ?>
  </strong></p>
</code>```

or I would recommend using using <?=*var* ?> since it looks cleaner

As Tom Scholz mentioned, if you are on a PHP version older then 5.4.0 you must set short_open_tag=on in your php.ini file

```<code><h4>Conference Registration</h4>
  <p><strong>
    <?=$confName.$confDate ?>
  </strong></p>
</code>```

Title: How to get php vars to display in html

Body:
I am executing a php script which collects some variables from a form, then displays a page from a MySQL table. The page is displayed fine, but the echoed variable are not.

Conference Registration

        <?php echo $confName $confDate; ?>

The expected result is that the two variable are displayed.
I tested that the variable were available by inserting an echo command at the top of the page.

The actual result is that the variable are not displayed.

When displaying the page source in the browser and hovering over the <?php line displayed in red, the following is displayed:

Saw "<p". Probable cause: Attempt to use an XML processing
  instruction in HTML. (XML procesing instructions are not supported in
  HTML.)

Body:
echo takes in a string or a list of strings PHP Manual

echo can accept

($confName, $confDate) (handles as a list)

$confName, $confDate (handles as a list)

$confName . $confDate (handles as a single string since it is concatenated)

so something like

<h4>Conference Registration</h4>
  <p><strong>
    <?php echo $confName, $confDate; ?>
  </strong></p>

or I would recommend using using <?=*var* ?> since it looks cleaner

As Tom Scholz mentioned, if you are on a PHP version older then 5.4.0 you must set short_open_tag=on in your php.ini file

<h4>Conference Registration</h4>
  <p><strong>
    <?=$confName.$confDate ?>
  </strong></p>


问:
Can't update from google play
In the last time when i'm trying to update my application from Google play, Google play avoid the update because I installed my app not from Google play, is there a solution how to update it anyway..?

Is it related to the new google play feature? "Let Google manage and protect your app signing key (recommended)"

答:
From where you installed the app first?
 a) Is it a build APK from Android Studio? Are you testing the app on your mobile device?
 b) Do you install the debug apk generated from Android Studio?
 c) Does the installed version has bigger Version code than the one on google play?

If a and b happens then You have to uninstall the app properly from your phone first. For that, you have to go to app info and then click on Right corner on the top and click Uninstall for all users(Mostly Android 6.0+)

If it option c then just uninstall the App and install the latest.

Remember One thing, App installed by Android Studio in the time of Testing is a debug apk, it is not signed. And App from playstore is signed. Two is not the same. That's why you can't update them.

Title: Can't update from google play


问:
Returning Json in AutoPilot with C#
I have poured over the documentation and read the related posts but I am still unable to successfully construct the Json for an Action array containing multiple elements.

The first element is a "Remember" action containing several elements of its own.  The second Action element is a "Collect" action.

I am able to add the first element but the second element eludes me.  The code I am posting contains errors. I am unable to add the second "Collect" element.  Am I close or way off?  Any guidance is greatly appreciated.

```<code>[HttpPost]
[Route("AcceptTask")]
internal string BuildAcceptCall(UserData ud)
{
    log.Debug("Entering BuildAcceptCall");
    var j = new
    {
        actions = new[]
        {
            new
           {
                remember = new
                   {
                         ud.AccountId,
                        EngineId = ud.EngineId,
                        ResidentTelephone = ud.ResidentTelephone,
                        OutboundCallerId = ud.OutboundCallerId,
                        UnitNumber = ud.UnitNumber,
                        BuildingNumber = ud.BuildingNumber,
                        Pets = ud.Pets,
                        Alarm = ud.Alarm,
                        EmergencyId = ud.EmergencyId,
                        CallDate = ud.CallDate,
                        WorkOrder = ud.WorkOrder,
                        CurrentLocation = ud.CurrentLocation
                   }, //close remember element

               collect = new
                {
                    name = "DidTechAcceptCall",
                    questions = new[]
                    {
                       new
                           {
                               question = "This is a maintenance call from Spring Meadows. will you accept the call?",
                               name = "OffferCallToTech",
                               type="Twilio.YES_NO"
                            }
                    },
                    on_complete = new
                    {
                        redirect = new
                        {
                            uri = @"https://8.40.212.131/MedsDispatch/api/Dispatch/EntryPoint_AutoPilot",
                            method = "post"
                        }
                    }
               }//close the collect element
            } //close the new
        }; //close the array

    string theObject = Newtonsoft.Json.JsonConvert.SerializeObject(j); ;
    return Newtonsoft.Json.JsonConvert.SerializeObject(j);

}

</code>```

答:
I highly recommend that you do one or all of the following

Use Twilio SDK for C# and .NET and Docs for creating a Task in C#.

Any kind of static task can be easily built off Twilio's AutoPilot Console

Anyways, here is the code

```<code>var j = new { actions = new object[]{
                new{
                    remember = new{
                        data = "data"
                    }
                },
                new{
                    collect = new{
                        name = "DidTechAcceptCall",
                        questions = new[]
                        {
                           new
                               {
                                   question = "This is a maintenance call from Spring Meadows. will you accept the call?",
                                   name = "OffferCallToTech",
                                   type="Twilio.YES_NO"
                                }
                        },
                        on_complete = new
                        {
                            redirect = new
                            {
                                uri = @"https://8.40.212.131/MedsDispatch/api/Dispatch/EntryPoint_AutoPilot",
                                method = "post"
                            }
                        }
                    }
                }
     }
};
string theObject = Newtonsoft.Json.JsonConvert.SerializeObject(j);
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(j));
</code>```

that produces

```<code>{
  "actions": [
    {
        "remember": {
            "data": "data"
        }
    },
    {
        "collect": {
            "name": "DidTechAcceptCall",
            "questions": [
                {
                    "question": "This is a maintenance call from Spring Meadows. will you accept the call?",
                    "name": "OffferCallToTech",
                    "type": "Twilio.YES_NO"
                }
            ],
            "on_complete": {
                "redirect": {
                    "uri": "https://8.40.212.131/MedsDispatch/api/Dispatch/EntryPoint_AutoPilot",
                    "method": "post"
                }
            }
        }
    }
  ]
}
</code>```

Title: Returning Json in AutoPilot with C#

Body:
I have poured over the documentation and read the related posts but I am still unable to successfully construct the Json for an Action array containing multiple elements.

The first element is a "Remember" action containing several elements of its own.  The second Action element is a "Collect" action.

I am able to add the first element but the second element eludes me.  The code I am posting contains errors. I am unable to add the second "Collect" element.  Am I close or way off?  Any guidance is greatly appreciated.

[HttpPost]
[Route("AcceptTask")]
internal string BuildAcceptCall(UserData ud)
{
    log.Debug("Entering BuildAcceptCall");
    var j = new
    {
        actions = new[]
        {
            new
           {
                remember = new
                   {
                         ud.AccountId,
                        EngineId = ud.EngineId,
                        ResidentTelephone = ud.ResidentTelephone,
                        OutboundCallerId = ud.OutboundCallerId,
                        UnitNumber = ud.UnitNumber,
                        BuildingNumber = ud.BuildingNumber,
                        Pets = ud.Pets,
                        Alarm = ud.Alarm,
                        EmergencyId = ud.EmergencyId,
                        CallDate = ud.CallDate,
                        WorkOrder = ud.WorkOrder,
                        CurrentLocation = ud.CurrentLocation
                   }, //close remember element

               collect = new
                {
                    name = "DidTechAcceptCall",
                    questions = new[]
                    {
                       new
                           {
                               question = "This is a maintenance call from Spring Meadows. will you accept the call?",
                               name = "OffferCallToTech",
                               type="Twilio.YES_NO"
                            }
                    },
                    on_complete = new
                    {
                        redirect = new
                        {
                            uri = @"https://8.40.212.131/MedsDispatch/api/Dispatch/EntryPoint_AutoPilot",
                            method = "post"
                        }
                    }
               }//close the collect element
            } //close the new
        }; //close the array

    string theObject = Newtonsoft.Json.JsonConvert.SerializeObject(j); ;
    return Newtonsoft.Json.JsonConvert.SerializeObject(j);

}

Body:
I highly recommend that you do one or all of the following

Use Twilio SDK for C# and .NET and Docs for creating a Task in C#.

Any kind of static task can be easily built off Twilio's AutoPilot Console

Anyways, here is the code

var j = new { actions = new object[]{
                new{
                    remember = new{
                        data = "data"
                    }
                },
                new{
                    collect = new{
                        name = "DidTechAcceptCall",
                        questions = new[]
                        {
                           new
                               {
                                   question = "This is a maintenance call from Spring Meadows. will you accept the call?",
                                   name = "OffferCallToTech",
                                   type="Twilio.YES_NO"
                                }
                        },
                        on_complete = new
                        {
                            redirect = new
                            {
                                uri = @"https://8.40.212.131/MedsDispatch/api/Dispatch/EntryPoint_AutoPilot",
                                method = "post"
                            }
                        }
                    }
                }
     }
};
string theObject = Newtonsoft.Json.JsonConvert.SerializeObject(j);
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(j));

that produces

{
  "actions": [
    {
        "remember": {
            "data": "data"
        }
    },
    {
        "collect": {
            "name": "DidTechAcceptCall",
            "questions": [
                {
                    "question": "This is a maintenance call from Spring Meadows. will you accept the call?",
                    "name": "OffferCallToTech",
                    "type": "Twilio.YES_NO"
                }
            ],
            "on_complete": {
                "redirect": {
                    "uri": "https://8.40.212.131/MedsDispatch/api/Dispatch/EntryPoint_AutoPilot",
                    "method": "post"
                }
            }
        }
    }
  ]
}