问:
how to color data points on a box plot by certain observations of a group in R
i'm trying to add colors to my data points on my boxplot based on a certain group but only a subset of observations within that group. For example:

I have a data set looks kind of like this

```<code>Value   Make   Location
40      Honda   USA
50      Toyota  CHINA
60      Ford    FRANCE
70      Subaru  CHINA
50      Honda   BRAZIL
50      Toyota  SPAIN
30      Nissan  CANADA
</code>```

i'm plotting a box plot looking at the value variable on the y axis and make variable on the x axis. Then i want to add all the data points to my boxplot and color only the ones where the location = china, brazil, and spain (all different colors) while the other data points that are not china, brazil, and spain would just be black.

This is my code:

```<code>library(ggplot2)

data %>% ggplot(aes(x=Make, y=Value)) +
         geom_boxplot() +
         geom_jitter(aes(color=Location))
</code>```

but this colors all the data points based on the location variable. i need the points colored only when location is china, brazil, and spain but still showing all the data points. how could i achieve this? any suggestions would be greatly appreciated!

答:
You can just create an extra column that says "Others" if it doesn't have the countries you want. Then, use scale_color_manual to enter the colors you want.

library(data.table)
df <- fread('Value   Make   Location
40      Honda   USA
50      Toyota  CHINA
60      Ford    FRANCE
70      Subaru  CHINA
50      Honda   BRAZIL
50      Toyota  SPAIN
30      Nissan  CANADA')

library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:data.table':
#>
#>     between, first, last
#> The following objects are masked from 'package:stats':
#>
#>     filter, lag
#> The following objects are masked from 'package:base':
#>
#>     intersect, setdiff, setequal, union
library(ggplot2)
visible_ctr <- c('BRAZIL','CHINA','SPAIN')
df %>%
  mutate(lcat=if_else(Location %in% visible_ctr,Location,'Others')) %>%
  mutate(lcat=factor(lcat,levels = c(visible_ctr,'Others'))) %>% # Reorder legend
  ggplot(aes(x=Make, y=Value)) +
  geom_boxplot() +
  geom_jitter(aes(color=lcat)) +
  scale_color_manual(values = c(BRAZIL='blue',CHINA='red',SPAIN='yellow',Others='black'))
```

Created on 2020-02-20 by the reprex package (v0.3.0)

Body:
i'm trying to add colors to my data points on my boxplot based on a certain group but only a subset of observations within that group. For example:

I have a data set looks kind of like this

Value   Make   Location
40      Honda   USA
50      Toyota  CHINA
60      Ford    FRANCE
70      Subaru  CHINA
50      Honda   BRAZIL
50      Toyota  SPAIN
30      Nissan  CANADA

i'm plotting a box plot looking at the value variable on the y axis and make variable on the x axis. Then i want to add all the data points to my boxplot and color only the ones where the location = china, brazil, and spain (all different colors) while the other data points that are not china, brazil, and spain would just be black.

This is my code:

library(ggplot2)

data %>% ggplot(aes(x=Make, y=Value)) +
         geom_boxplot() +
         geom_jitter(aes(color=Location))

but this colors all the data points based on the location variable. i need the points colored only when location is china, brazil, and spain but still showing all the data points. how could i achieve this? any suggestions would be greatly appreciated!

Body:
You can just create an extra column that says "Others" if it doesn't have the countries you want. Then, use scale_color_manual to enter the colors you want.

library(data.table)
df <- fread('Value   Make   Location
40      Honda   USA
50      Toyota  CHINA
60      Ford    FRANCE
70      Subaru  CHINA
50      Honda   BRAZIL
50      Toyota  SPAIN
30      Nissan  CANADA')

library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:data.table':
#>
#>     between, first, last
#> The following objects are masked from 'package:stats':
#>
#>     filter, lag
#> The following objects are masked from 'package:base':
#>
#>     intersect, setdiff, setequal, union
library(ggplot2)
visible_ctr <- c('BRAZIL','CHINA','SPAIN')
df %>%
  mutate(lcat=if_else(Location %in% visible_ctr,Location,'Others')) %>%
  mutate(lcat=factor(lcat,levels = c(visible_ctr,'Others'))) %>% # Reorder legend
  ggplot(aes(x=Make, y=Value)) +
  geom_boxplot() +
  geom_jitter(aes(color=lcat)) +
  scale_color_manual(values = c(BRAZIL='blue',CHINA='red',SPAIN='yellow',Others='black'))

Created on 2020-02-20 by the reprex package (v0.3.0)


来源: stackexchange

问:
I'm not receiving firebase notifications on my iOS Device
I'm not receiving Firebase Notifications on my iOS Device. I have tried changing many aspects of the code to no avail. I also tried to run the app on both a simulator and a phone but it the notify don't show up on either. I am following Firebase Documentation but it's still not working. Here's my AppDelegate File:</p>

```<code>@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    let gcmMessageIDKey = "gcm.message_id"

    func applicationDidBecomeActive(_ application: UIApplication) {
    }

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
           SDKApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)

        if #available(iOS 10.0, *) {
          // For iOS 10 display notification (sent via APNS)
          UNUserNotificationCenter.current().delegate = self

          let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
          UNUserNotificationCenter.current().requestAuthorization(
            options: authOptions,
            completionHandler: {_, _ in })

            Messaging.messaging().delegate = self

        } else {
          let settings: UIUserNotificationSettings =
          UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
          application.registerUserNotificationSettings(settings)
        }

        application.registerForRemoteNotifications()

        FirebaseApp.configure()

        return true
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
      // 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)

      // Print message ID.
      if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
      }

      // Print full message.
      print(userInfo)
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                     fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
      // 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)

      // Print message ID.
      if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
      }

      // Print full message.
      print(userInfo)

      completionHandler(UIBackgroundFetchResult.newData)
    }

}

@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {

  // Receive displayed notifications for iOS 10 devices.
  func userNotificationCenter(_ center: UNUserNotificationCenter,
                              willPresent notification: UNNotification,
    withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let userInfo = notification.request.content.userInfo

    // With swizzling disabled you must let Messaging know about the message, for Analytics
    // Messaging.messaging().appDidReceiveMessage(userInfo)

    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
      print("Message ID: \(messageID)")
    }

    // Print full message.
    print(userInfo)

    // Change this to your preferred presentation option
    completionHandler([])
  }

  func userNotificationCenter(_ center: UNUserNotificationCenter,
                              didReceive response: UNNotificationResponse,
                              withCompletionHandler completionHandler: @escaping () -> Void) {
    let userInfo = response.notification.request.content.userInfo
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
      print("Message ID: \(messageID)")
    }

    // Print full message.
    print(userInfo)

    completionHandler()
  }
}

extension AppDelegate:MessagingDelegate {

 func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
      print("Firebase registration token: \(fcmToken)")

      let dataDict:[String: String] = ["token": fcmToken]
      NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
      // TODO: If necessary send token to application server.
      // Note: This callback is fired at each app startup and whenever a new token is generated.
    }

    func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
        print("Message Data:  ", remoteMessage.appData)
    }
}
</code>```

答:
Handling Push Notifications :-

I'm posting this solution as it worked for me.But before use this please do check that you have uploaded right APNs authentication key under iOS app configuration on console.
- Go to your AppDelegate file.
- Step 1: Write this code inside this function:

```<code>@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var application : UIApplication?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        ApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)

        FirebaseApp.configure()

        if #available(iOS 10.0, *) {
            // For iOS 10 display notification (sent via APNS)
            UNUserNotificationCenter.current().delegate = self

            Messaging.messaging().delegate = self

            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
            UNUserNotificationCenter.current().requestAuthorization(
                options: authOptions,
                completionHandler: {_, _ in })
        } else {
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }

        application.registerForRemoteNotifications()

        return true
    }

    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        _ = (deviceToken as NSData).bytes.bindMemory(to: CChar.self, capacity: deviceToken.count)
        var token = ""
        token = /Messaging.messaging().fcmToken
        print("FCM token: \(token )")
        Messaging.messaging().apnsToken = deviceToken
    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Did Fail to Register for Remote Notifications")
        print("\(error), \(error.localizedDescription)")
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {

        print("didReceiveRemoteNotification \(userInfo)")
    }
}

@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {

    // Receive displayed notifications for iOS 10 devices.
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

        let userInfo = notification.request.content.userInfo

        print("======== messafe received %@", userInfo)

       //handle push notification

        completionHandler([.alert, .badge, .sound])
    }

    @available(iOS 10, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

        switch UIApplication.shared.applicationState {
        case .active:

            break
        case .background, .inactive :

            let userInfo = response.notification.request.content.userInfo

           //handle push notification
            break

        default:

            break
        }
        completionHandler()
    }

    func performNotificationAction(userInfo : [AnyHashable : Any], completion : (UNNotificationPresentationOptions) -> ()) {

        if UIApplication.shared.applicationState == .active || UIApplication.shared.applicationState == .background {

        }

        else if UIApplication.shared.applicationState == .inactive {

        }
    }

    func pushNavigation(userInfo : [AnyHashable : Any], completion : (UNNotificationPresentationOptions) -> ()) {

    }
}
extension AppDelegate : MessagingDelegate {

    public func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {

    }

    public func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {

        print(fcmToken)
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm not receiving Firebase Notifications on my iOS Device. I have tried changing many aspects of the code to no avail. I also tried to run the app on both a simulator and a phone but it the notify don't show up on either. I am following Firebase Documentation but it's still not working. Here's my AppDelegate File:

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    let gcmMessageIDKey = "gcm.message_id"

    func applicationDidBecomeActive(_ application: UIApplication) {
    }

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
           SDKApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)

        if #available(iOS 10.0, *) {
          // For iOS 10 display notification (sent via APNS)
          UNUserNotificationCenter.current().delegate = self

          let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
          UNUserNotificationCenter.current().requestAuthorization(
            options: authOptions,
            completionHandler: {_, _ in })

            Messaging.messaging().delegate = self

        } else {
          let settings: UIUserNotificationSettings =
          UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
          application.registerUserNotificationSettings(settings)
        }

        application.registerForRemoteNotifications()

        FirebaseApp.configure()

        return true
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
      // 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)

      // Print message ID.
      if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
      }

      // Print full message.
      print(userInfo)
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                     fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
      // 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)

      // Print message ID.
      if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
      }

      // Print full message.
      print(userInfo)

      completionHandler(UIBackgroundFetchResult.newData)
    }

}

@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {

  // Receive displayed notifications for iOS 10 devices.
  func userNotificationCenter(_ center: UNUserNotificationCenter,
                              willPresent notification: UNNotification,
    withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let userInfo = notification.request.content.userInfo

    // With swizzling disabled you must let Messaging know about the message, for Analytics
    // Messaging.messaging().appDidReceiveMessage(userInfo)

    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
      print("Message ID: \(messageID)")
    }

    // Print full message.
    print(userInfo)

    // Change this to your preferred presentation option
    completionHandler([])
  }

  func userNotificationCenter(_ center: UNUserNotificationCenter,
                              didReceive response: UNNotificationResponse,
                              withCompletionHandler completionHandler: @escaping () -> Void) {
    let userInfo = response.notification.request.content.userInfo
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
      print("Message ID: \(messageID)")
    }

    // Print full message.
    print(userInfo)

    completionHandler()
  }
}

extension AppDelegate:MessagingDelegate {

 func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
      print("Firebase registration token: \(fcmToken)")

      let dataDict:[String: String] = ["token": fcmToken]
      NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
      // TODO: If necessary send token to application server.
      // Note: This callback is fired at each app startup and whenever a new token is generated.
    }

    func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
        print("Message Data:  ", remoteMessage.appData)
    }
}

Body:
Handling Push Notifications :-

I'm posting this solution as it worked for me.But before use this please do check that you have uploaded right APNs authentication key under iOS app configuration on console.
- Go to your AppDelegate file.
- Step 1: Write this code inside this function:

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var application : UIApplication?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        ApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)

        FirebaseApp.configure()

        if #available(iOS 10.0, *) {
            // For iOS 10 display notification (sent via APNS)
            UNUserNotificationCenter.current().delegate = self

            Messaging.messaging().delegate = self

            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
            UNUserNotificationCenter.current().requestAuthorization(
                options: authOptions,
                completionHandler: {_, _ in })
        } else {
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }

        application.registerForRemoteNotifications()

        return true
    }

    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        _ = (deviceToken as NSData).bytes.bindMemory(to: CChar.self, capacity: deviceToken.count)
        var token = ""
        token = /Messaging.messaging().fcmToken
        print("FCM token: \(token )")
        Messaging.messaging().apnsToken = deviceToken
    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Did Fail to Register for Remote Notifications")
        print("\(error), \(error.localizedDescription)")
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {

        print("didReceiveRemoteNotification \(userInfo)")
    }
}

@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {

    // Receive displayed notifications for iOS 10 devices.
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

        let userInfo = notification.request.content.userInfo

        print("======== messafe received %@", userInfo)

       //handle push notification

        completionHandler([.alert, .badge, .sound])
    }

    @available(iOS 10, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

        switch UIApplication.shared.applicationState {
        case .active:

            break
        case .background, .inactive :

            let userInfo = response.notification.request.content.userInfo

           //handle push notification
            break

        default:

            break
        }
        completionHandler()
    }

    func performNotificationAction(userInfo : [AnyHashable : Any], completion : (UNNotificationPresentationOptions) -> ()) {

        if UIApplication.shared.applicationState == .active || UIApplication.shared.applicationState == .background {

        }

        else if UIApplication.shared.applicationState == .inactive {

        }
    }

    func pushNavigation(userInfo : [AnyHashable : Any], completion : (UNNotificationPresentationOptions) -> ()) {

    }
}
extension AppDelegate : MessagingDelegate {

    public func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {

    }

    public func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {

        print(fcmToken)
    }
}


问:
Gradient is None is Pytorch
For the following code, I would wish to get the gradient by get_grads(), but the output is always None, what is the reason?

import torch
import torch.nn as nn
import matplotlib.pyplot as plt
import numpy as np

X = torch.randn(100, 1)*10  #random with 100rows*1col, *10 to make it larger (original is small variance around 0)
y = X + 3*torch.randn(100, 1) #3*torch.randn(100, 1), it's the noise
plt.plot(X.numpy(), y.numpy(), 'o')
plt.ylabel('y')
plt.xlabel('x')

class LR(nn.Module):
  def __init__(self, input_size, output_size):
    super().__init__()
    self.linear = nn.Linear(input_size, output_size)
  def forward(self, x):
    pred = self.linear(x)
    return pred

torch.manual_seed(1)
model = LR(1, 1)

[w, b] = model.parameters()
def get_params():
  return (w[0][0].item(), b[0].item())
def get_grads():
  return (w[0][0].grad, b[0].grad)

criterion = nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), lr = 0.01)

epochs = 30
losses = []
for i in range(epochs):
  y_pred = model.forward(X)
  loss = criterion(y_pred, y)
  print("epoch:", i, "loss:", loss.item())

  losses.append(loss)
  optimizer.zero_grad() #clear gradient for parameter]
  print("model=" + str(get_params())+str(get_grads()))
  loss.backward() #calculate gradient for parameters
  print("model2=" + str(get_params())+str(get_grads()))
  optimizer.step() #update the parameters with gradient
  print("model3=" + str(get_params())+str(get_grads()))
  print()
```

<p>Output</p>

<pre class="lang-py prettyprint-override"><code>epoch: 0 loss: 31.3035831451416
model=(0.5152631998062134, -0.44137823581695557)(None, None)
model2=(0.5152631998062134, -0.44137823581695557)(None, None)
model3=(1.447475790977478, -0.4449453055858612)(None, None)

epoch: 1 loss: 31.142377853393555
model=(1.447475790977478, -0.4449453055858612)(None, None)
model2=(1.447475790977478, -0.4449453055858612)(None, None)
model3=(0.5188075304031372, -0.41897052526474)(None, None)

epoch: 2 loss: 30.982675552368164
model=(0.5188075304031372, -0.41897052526474)(None, None)
model2=(0.5188075304031372, -0.41897052526474)(None, None)
model3=(1.4446537494659424, -0.42287370562553406)(None, None)

epoch: 3 loss: 30.824453353881836
model=(1.4446537494659424, -0.42287370562553406)(None, None)
model2=(1.4446537494659424, -0.42287370562553406)(None, None)
model3=(0.5223162770271301, -0.39742958545684814)(None, None)

epoch: 4 loss: 30.667678833007812
model=(0.5223162770271301, -0.39742958545684814)(None, None)
model2=(0.5223162770271301, -0.39742958545684814)(None, None)
model3=(1.4418396949768066, -0.40165263414382935)(None, None)

epoch: 5 loss: 30.51233673095703
model=(1.4418396949768066, -0.40165263414382935)(None, None)
model2=(1.4418396949768066, -0.40165263414382935)(None, None)
model3=(0.5257899761199951, -0.37672188878059387)(None, None)

epoch: 6 loss: 30.358415603637695
model=(0.5257899761199951, -0.37672188878059387)(None, None)
model2=(0.5257899761199951, -0.37672188878059387)(None, None)
model3=(1.4390342235565186, -0.3812492787837982)(None, None)

epoch: 7 loss: 30.205856323242188
model=(1.4390342235565186, -0.3812492787837982)(None, None)
model2=(1.4390342235565186, -0.3812492787837982)(None, None)
model3=(0.5292295813560486, -0.35681530833244324)(None, None)

epoch: 8 loss: 30.054668426513672
model=(0.5292295813560486, -0.35681530833244324)(None, None)
model2=(0.5292295813560486, -0.35681530833244324)(None, None)
model3=(1.4362375736236572, -0.3616321086883545)(None, None)

epoch: 9 loss: 29.904821395874023
model=(1.4362375736236572, -0.3616321086883545)(None, None)
model2=(1.4362375736236572, -0.3616321086883545)(None, None)
model3=(0.532635509967804, -0.3376788794994354)(None, None)

epoch: 10 loss: 29.756284713745117
model=(0.532635509967804, -0.3376788794994354)(None, None)
model2=(0.532635509967804, -0.3376788794994354)(None, None)
model3=(1.4334499835968018, -0.3427707254886627)(None, None)

epoch: 11 loss: 29.609052658081055
model=(1.4334499835968018, -0.3427707254886627)(None, None)
model2=(1.4334499835968018, -0.3427707254886627)(None, None)
model3=(0.5360085964202881, -0.3192828297615051)(None, None)
...
</code>```

答:
You need to get the gradients directly as w.grad and b.grad, not w[0][0].grad as follows:

```<code>def get_grads():
  return (w.grad, b.grad)
</code>```

OR you can also use the name of the parameter directly in the training loop to print its gradient:

```<code>print(model.linear.weight.grad)
print(model.linear.bias.grad)
</code>```

Title: Gradient is None is Pytorch

Body:
For the following code, I would wish to get the gradient by get_grads(), but the output is always None, what is the reason?

import torch
import torch.nn as nn
import matplotlib.pyplot as plt
import numpy as np

X = torch.randn(100, 1)*10  #random with 100rows*1col, *10 to make it larger (original is small variance around 0)
y = X + 3*torch.randn(100, 1) #3*torch.randn(100, 1), it's the noise
plt.plot(X.numpy(), y.numpy(), 'o')
plt.ylabel('y')
plt.xlabel('x')

class LR(nn.Module):
  def __init__(self, input_size, output_size):
    super().__init__()
    self.linear = nn.Linear(input_size, output_size)
  def forward(self, x):
    pred = self.linear(x)
    return pred

torch.manual_seed(1)
model = LR(1, 1)

[w, b] = model.parameters()
def get_params():
  return (w[0][0].item(), b[0].item())
def get_grads():
  return (w[0][0].grad, b[0].grad)

criterion = nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), lr = 0.01)

epochs = 30
losses = []
for i in range(epochs):
  y_pred = model.forward(X)
  loss = criterion(y_pred, y)
  print("epoch:", i, "loss:", loss.item())

  losses.append(loss)
  optimizer.zero_grad() #clear gradient for parameter]
  print("model=" + str(get_params())+str(get_grads()))
  loss.backward() #calculate gradient for parameters
  print("model2=" + str(get_params())+str(get_grads()))
  optimizer.step() #update the parameters with gradient
  print("model3=" + str(get_params())+str(get_grads()))
  print()

Output

epoch: 0 loss: 31.3035831451416
model=(0.5152631998062134, -0.44137823581695557)(None, None)
model2=(0.5152631998062134, -0.44137823581695557)(None, None)
model3=(1.447475790977478, -0.4449453055858612)(None, None)

epoch: 1 loss: 31.142377853393555
model=(1.447475790977478, -0.4449453055858612)(None, None)
model2=(1.447475790977478, -0.4449453055858612)(None, None)
model3=(0.5188075304031372, -0.41897052526474)(None, None)

epoch: 2 loss: 30.982675552368164
model=(0.5188075304031372, -0.41897052526474)(None, None)
model2=(0.5188075304031372, -0.41897052526474)(None, None)
model3=(1.4446537494659424, -0.42287370562553406)(None, None)

epoch: 3 loss: 30.824453353881836
model=(1.4446537494659424, -0.42287370562553406)(None, None)
model2=(1.4446537494659424, -0.42287370562553406)(None, None)
model3=(0.5223162770271301, -0.39742958545684814)(None, None)

epoch: 4 loss: 30.667678833007812
model=(0.5223162770271301, -0.39742958545684814)(None, None)
model2=(0.5223162770271301, -0.39742958545684814)(None, None)
model3=(1.4418396949768066, -0.40165263414382935)(None, None)

epoch: 5 loss: 30.51233673095703
model=(1.4418396949768066, -0.40165263414382935)(None, None)
model2=(1.4418396949768066, -0.40165263414382935)(None, None)
model3=(0.5257899761199951, -0.37672188878059387)(None, None)

epoch: 6 loss: 30.358415603637695
model=(0.5257899761199951, -0.37672188878059387)(None, None)
model2=(0.5257899761199951, -0.37672188878059387)(None, None)
model3=(1.4390342235565186, -0.3812492787837982)(None, None)

epoch: 7 loss: 30.205856323242188
model=(1.4390342235565186, -0.3812492787837982)(None, None)
model2=(1.4390342235565186, -0.3812492787837982)(None, None)
model3=(0.5292295813560486, -0.35681530833244324)(None, None)

epoch: 8 loss: 30.054668426513672
model=(0.5292295813560486, -0.35681530833244324)(None, None)
model2=(0.5292295813560486, -0.35681530833244324)(None, None)
model3=(1.4362375736236572, -0.3616321086883545)(None, None)

epoch: 9 loss: 29.904821395874023
model=(1.4362375736236572, -0.3616321086883545)(None, None)
model2=(1.4362375736236572, -0.3616321086883545)(None, None)
model3=(0.532635509967804, -0.3376788794994354)(None, None)

epoch: 10 loss: 29.756284713745117
model=(0.532635509967804, -0.3376788794994354)(None, None)
model2=(0.532635509967804, -0.3376788794994354)(None, None)
model3=(1.4334499835968018, -0.3427707254886627)(None, None)

epoch: 11 loss: 29.609052658081055
model=(1.4334499835968018, -0.3427707254886627)(None, None)
model2=(1.4334499835968018, -0.3427707254886627)(None, None)
model3=(0.5360085964202881, -0.3192828297615051)(None, None)
...

Body:
You need to get the gradients directly as w.grad and b.grad, not w[0][0].grad as follows:

def get_grads():
  return (w.grad, b.grad)

OR you can also use the name of the parameter directly in the training loop to print its gradient:

print(model.linear.weight.grad)
print(model.linear.bias.grad)


问:
error document not geting redirect in wamp server
I'm using wamp server 3.0.4 and apache version 2.4.18.I want to redirect 404 pages to custom pages. I have enabled LoadModule rewrite_module modules/mod_rewrite.so in apache/conf/httpd.conf and changed in apache/conf/httpd.conf:

```<code><Directory "c:/wamp64/www/">
Options +Indexes +FollowSymLinks
AllowOverride all  #none to all
Require local
</Directory>
</code>```

In httpd.vhost

```<code><VirtualHost *:80>
    ServerName testblog
    DocumentRoot c:/wamp64/www/testblog
    <Directory  "c:/wamp64/www/testblog/">
        Options +Indexes +FollowSymLinks +MultiViews
        AllowOverride All
        Require local
    </Directory>
</VirtualHost>
</code>```

and restart the server.

In my htaccess file I have the following code

```<code>ErrorDocument 404 https://www.test.com/not-found.html

RedirectMatch 301 /learn   https://www.test.com/not-found.html
</code>```

But not able to redirect .What I missed here

答:
Keep mod_rewrite enabled and then trying this in your .htaccess file:

Add the following to it at the top:

```<code>RewriteEngine On
RewriteBase /
RewriteRule ^learn https://www.test.com/not-found.html [R=302,L]
</code>```

RedirectMatch uses mod_alias, so make sure you have enabled that, it should be enabled automatically, but rarely it might not be, so enable it and try your redirect. Even after that, if it does not work, stick with the above. Let me know if you have any questions.

Body:
I'm using wamp server 3.0.4 and apache version 2.4.18.I want to redirect 404 pages to custom pages. I have enabled LoadModule rewrite_module modules/mod_rewrite.so in apache/conf/httpd.conf and changed in apache/conf/httpd.conf:

<Directory "c:/wamp64/www/">
Options +Indexes +FollowSymLinks
AllowOverride all  #none to all
Require local
</Directory>

In httpd.vhost

<VirtualHost *:80>
    ServerName testblog
    DocumentRoot c:/wamp64/www/testblog
    <Directory  "c:/wamp64/www/testblog/">
        Options +Indexes +FollowSymLinks +MultiViews
        AllowOverride All
        Require local
    </Directory>
</VirtualHost>

and restart the server.

In my htaccess file I have the following code

ErrorDocument 404 https://www.test.com/not-found.html

RedirectMatch 301 /learn   https://www.test.com/not-found.html

But not able to redirect .What I missed here

Body:
Keep mod_rewrite enabled and then trying this in your .htaccess file:

Add the following to it at the top:

RewriteEngine On
RewriteBase /
RewriteRule ^learn https://www.test.com/not-found.html [R=302,L]

RedirectMatch uses mod_alias, so make sure you have enabled that, it should be enabled automatically, but rarely it might not be, so enable it and try your redirect. Even after that, if it does not work, stick with the above. Let me know if you have any questions.


问:
Adding the result of separate results
Thanks in advance for any replies. I am new to JavaScript and have got this far in calculating 2 results that I require. My question is how do I add both results together?

Please see first result below:

```<code>$(document).ready(function() {
    function checkSum(e) {
        var result = 0;
        $(".checksum").each(function() {
            var i = 0;
            if ($(this).val() != "") {
                i = parseFloat($(this).val());
            }

            result = result + i;
        });
        $("#resultsum").html(result * 60.60);
    }

    checkSum();
    $(".checksum").bind("keyup", checkSum);

});
</code>```

and this is the second:

```<code>$(document).ready(function() {

    function checkSum2(e) {
        var result2 = 0;
        $(".checksum2").each(function() {
            var j = 0;
            if ($(this).val() != "") {
                j = parseFloat($(this).val());
            }

            result2 = result2 + j;
        });
        $("#resultsum2").html(result2 * 14.88);
    }
    checkSum2();
    $(".checksum2").bind("keyup", checkSum2);

});
</code>```

答:
Just add one line in the end of functions:

```<code>$("#resultsum3").html($("#resultsum").text() + $("#resultsum2").text());
</code>```

```<code>$(document).ready(function() {
    function checkSum(e) {
        var result = 0;
        $(".checksum").each(function() {
            var i = 0;
            if ($(this).val() != "") {
                i = parseFloat($(this).val());
            }

            result = result + i;
        });
        $("#resultsum").html(result * 60.60);
      $("#resultsum3").html($("#resultsum").text() + $("#resultsum2").text());
    }

    checkSum();
    $(".checksum").bind("keyup", checkSum);
    function checkSum2(e) {
        var result2 = 0;
        $(".checksum2").each(function() {
            var j = 0;
            if ($(this).val() != "") {
                j = parseFloat($(this).val());
            }

            result2 = result2 + j;
        });
        $("#resultsum2").html(result2 * 14.88);
      $("#resultsum3").html($("#resultsum").text() + $("#resultsum2").text());
    }
    checkSum2();
    $(".checksum2").bind("keyup", checkSum2);

});
</code>```

Title: Adding the result of separate results

Body:
Thanks in advance for any replies. I am new to JavaScript and have got this far in calculating 2 results that I require. My question is how do I add both results together?

Please see first result below:

$(document).ready(function() {
    function checkSum(e) {
        var result = 0;
        $(".checksum").each(function() {
            var i = 0;
            if ($(this).val() != "") {
                i = parseFloat($(this).val());
            }

            result = result + i;
        });
        $("#resultsum").html(result * 60.60);
    }

    checkSum();
    $(".checksum").bind("keyup", checkSum);

});

and this is the second:

$(document).ready(function() {

    function checkSum2(e) {
        var result2 = 0;
        $(".checksum2").each(function() {
            var j = 0;
            if ($(this).val() != "") {
                j = parseFloat($(this).val());
            }

            result2 = result2 + j;
        });
        $("#resultsum2").html(result2 * 14.88);
    }
    checkSum2();
    $(".checksum2").bind("keyup", checkSum2);

});

Body:
Just add one line in the end of functions:

$("#resultsum3").html($("#resultsum").text() + $("#resultsum2").text());

$(document).ready(function() {
    function checkSum(e) {
        var result = 0;
        $(".checksum").each(function() {
            var i = 0;
            if ($(this).val() != "") {
                i = parseFloat($(this).val());
            }

            result = result + i;
        });
        $("#resultsum").html(result * 60.60);
      $("#resultsum3").html($("#resultsum").text() + $("#resultsum2").text());
    }

    checkSum();
    $(".checksum").bind("keyup", checkSum);
    function checkSum2(e) {
        var result2 = 0;
        $(".checksum2").each(function() {
            var j = 0;
            if ($(this).val() != "") {
                j = parseFloat($(this).val());
            }

            result2 = result2 + j;
        });
        $("#resultsum2").html(result2 * 14.88);
      $("#resultsum3").html($("#resultsum").text() + $("#resultsum2").text());
    }
    checkSum2();
    $(".checksum2").bind("keyup", checkSum2);

});


问:
Find mean of list in F#
I'm trying to find the average of a list

Here's what I have so far

```<code>let rec avg aList =
    match aList with
    | head::tail -> head+avg(tail)
    | [] -> 0

</code>```

This obtains the sum. I've tried head+avg(tail)/aList.Length, but it gives me an incorrect result as I don't know exactly what that's doing

Any help would be appreciated

答:
```<code>let avg aList =
    let rec sum = function
        | head :: tail -> head + (sum tail)
        | [] -> 0.
    sum aList / (aList |> List.length |> float)

let res = avg [ 2.; 4.; 6. ]
printfn "%A" res
</code>```

I'm not sure this is the best way to do it tho.

Title: Find mean of list in F#

Body:
I'm trying to find the average of a list

Here's what I have so far

let rec avg aList =
    match aList with
    | head::tail -> head+avg(tail)
    | [] -> 0

This obtains the sum. I've tried head+avg(tail)/aList.Length, but it gives me an incorrect result as I don't know exactly what that's doing

Any help would be appreciated

Body:
let avg aList =
    let rec sum = function
        | head :: tail -> head + (sum tail)
        | [] -> 0.
    sum aList / (aList |> List.length |> float)

let res = avg [ 2.; 4.; 6. ]
printfn "%A" res

I'm not sure this is the best way to do it tho.


问:
How can I create a bootstrapper which will install 3rd party exe followed by 2 msi apps
Im inexperienced with creating setup projects and was hoping for some direction regarding the best, most flexible, and easiest way of creating a setup bootstrapper. I need custom actions to check for existing versions, ability to install 3rd party application, several inhouse msi applications etc.
Currently I've considered the following options, installshield, VS setup project, msbuild, wix. But after a couple days searching still looking for the recommended approach here.
Any advice appreciated</p>

答:
Most of the tools you mentioned support what you want in one way or another. It really depends on what you want to use.

If you want a free solution, Wix is the best. It's not so easy to configure prerequisites with it, but it can be done:
http://wix.sourceforge.net/manual-wix3/install_dotnet.htm

If you want a commercial solution, I recommend Advanced Installer or InstallShield. You need to purchase a license, but you can configure your installer with a couple of clicks.

So you should first decide on what tool you want to use and then see if you encounter any problems.

ContentLicense: CC BY-SA 3.0


问:
How to insert data with subquery using SELECT * as VALUE?
I have 2 queries.
First query is

```<code>SELECT date
FROM tableA
WHERE
    db='mydb' AND
    date > (SELECT MAX(date) FROM tableB WHERE db='mydb')
LIMIT 1;
</code>```

Second query is

```<code>INSERT INTO tableB (date, db, comment)
SELECT * FROM tableA
WHERE
    db = 'mydb' AND
    date = (date that i got from first query);
</code>```

Data types are:
db(VARCHAR), date(date), comment(mediumblob).

statement SELECT * FROM tableA WHERE db = 'mydb' AND date = (date that i got from first query); returns exactly 1 row, but somehow second query returns that 1242 - Subquery returns more than 1 row.

I have tried to change SELECT * statement to each columns, but it didn't work on column comment. And it is impossible to do this on trigger because tableA is in system table.

答:
As far as I understand the goal, you are trying to copy all fresh values from A to B. Here "fresh" means "date not exists in the target table yet".

I think it can be simplified to this query:

INSERT INTO `tableB` (`date`, `db`, `comment`)
SELECT `date`, `db`, `comment`
FROM `tableA`
WHERE `db` = 'mydb'
AND `date` > (SELECT MAX(`date`) FROM `tableB` WHERE `db` = 'mydb')
```

Body:
I have 2 queries.
First query is

SELECT date
FROM tableA
WHERE
    db='mydb' AND
    date > (SELECT MAX(date) FROM tableB WHERE db='mydb')
LIMIT 1;

Second query is

INSERT INTO tableB (date, db, comment)
SELECT * FROM tableA
WHERE
    db = 'mydb' AND
    date = (date that i got from first query);

Data types are:
db(VARCHAR), date(date), comment(mediumblob).

statement SELECT * FROM tableA WHERE db = 'mydb' AND date = (date that i got from first query); returns exactly 1 row, but somehow second query returns that 1242 - Subquery returns more than 1 row.

I have tried to change SELECT * statement to each columns, but it didn't work on column comment. And it is impossible to do this on trigger because tableA is in system table.


问:
Make Jenkins node offline if job passes
Is there any script or plugin so that I can take Jenkins node offline automatically if the job passes.
Or if i explicitly give choice parameter to take node offline after current build.</p>

答:
I mentioned before an API for disconnecting a node: see more at "Monitor and Restart Offline Slaves".

That means you can add a post-build action, which would call this api though curl.

Title: Make Jenkins node offline if job passes


问:
Python Opencv: Filter Image for Text Detection

I have these set of images I want to de-noise in order to run OCR on :

I am trying to read the 1973 from the image.

I have tried

```<code>import cv2,numpy as np

img=cv2.imread('uxWbP.png',0)
img = cv2.resize(img, (0, 0), fx=2, fy=2)
copy_img=np.copy(img)
#adaptive threshold as the image has different lighting conditions in different areas
thresh = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 21, 2)

contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
#kill small contours
for i_cnt, cnt in enumerate(sorted(contours, key=lambda x: cv2.boundingRect(x)[0])):
    _area = cv2.contourArea(cnt)
    x, y, w, h = cv2.boundingRect(cnt)
    x_y_area = w * h
    if 10000 < x_y_area and x_y_area < 400000:
        pass
        # cv2.rectangle(copy_img, (x, y), (x + w, y + h), (255, 0, 255), 2)
        # cv2.putText(copy_img, str(int(x_y_area)) + ' , ' + str(w) + ' , ' + str(h), (x, y + 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)
        # cv2.drawContours(copy_img, [cnt], 0, (0, 255, 0), 1)
    elif 10000 > x_y_area:
        #write over small contours
        cv2.drawContours(thresh, [cnt], -1, 255, -1)

cv2.imshow('img',copy_img)
cv2.imshow('thresh',thresh)
cv2.waitKey(0)
</code>```

Which significantly improves the image to:

Any recommendations on how to filter this image sufficiently either on improvements to the filtered image or complete change from the start, that I could run OCR or some ML detection scripts on this? I'd like to split out the numbers for detection, but open to other methods as well.

答:
Another thing to try - either separately from the blurring (or in combination with it - is the erosion/dilation game, as hinted at in the comment by @eldesgraciado , to whom I think a good part of the credit for these answers should go.

These two (erosion and dilation) can be applied one after the other, repeatedly. I think the trick is to change the kernel size. Anyway, I know I've used that to reduce noise in the past. Here's one example of dilation:

>>> import cv2
>>> import numpy as np
>>> im_0 = cv2.imread("FWM8b.png")
>>> k_size = 3
>>> kernel = np.ones((k_size, k_size), np.uint8)
>>> im_dilated = cv2.dilate(im_0, kernel, iterations=1)
>>> cv2.imshow("d", im_dilated)
>>> cv2.waitKey(0)
```

<p><img src="https://i.stack.imgur.com/zCB6b.png" alt="Quick Dilation"></p>

<p>Make whatever kernel you want for erosion, and check out the effects.</p>

<pre class="lang-py prettyprint-override"><code>>>> im_eroded = cv2.erode(im_0, kernel, iterations=1)
>>> cv2.imshow("erosion", im_eroded)
>>> cv2.waitKey(0)
</code>```

Edit with possible improvements:

>>> im_blurred = cv2.GaussianBlur(im_dilated, (0, 0), 3)
>>> im_better = cv2.addWeighted(im_0, 0.5, im_blurred, 1.2, 0)
# Getting closer.
```

<p><img src="https://i.stack.imgur.com/wf43X.png" alt="Dilated, blurred, and combined with original, 1st"></p>

<p>^ <strong>d</strong>ilated, <strong>b</strong>lurred, and combined (<strong>a</strong>dded) with original, <strong>1</strong>st way</p>

<hr/>

<pre class="lang-py prettyprint-override"><code># Even better, I think.
im_better2 = cv2.addWeighted(im_0, 0.9, im_blurred, 1.7, 0)
</code>```

^ dilated, blurred, and combined (added) with original, 2nd way

You could do artifact removal, but be careful not to get rid of the stalk of the 7. If you can keep the 7 together, you can do connected-component analysis and keep the biggest connected components.

You could sum the values of pixels on each column and each row, which would probably lead to something like this (very approximated - almost time for work). Note that I was much more careful with the green curve - sums of columns - but the consistency of scaling is probably off.

Note that this is more a sum of (255 - pixel_value). That could find you rectangles where your to-be-found glyphs (digits) should be. You could do a 2-d map of column_pixel_sum + row_pixel_sum, or just do some approximation, as I have done below.

Also to feel free to rotate the image (or take pixel sums at different angles), and combine your info for each rotation.

Lots of other things to try ... the suggestion by @eldesgraciado of a noise model is especially intriguing.

Another thing you could try out is to create a "noise model" and subtract it from the original image. First, take the image and apply Gaussian Blur with very low parameters, just barely blurring it, next subtract this mask from the image. From here, the steps are experimental: The difference should be again blurred and thresholded. Save this image. You run this pre-processing with various parameters and saving each time the final binary image, then, average the masks obtained so far. The persistent blobs should be the ones you are looking for... like some sort of spatial bandstop, I guess...

Keep experimenting.

Unsharp mask (my other answer) on this result image. More noise gone, but hurts the 7.

Body:
I have these set of images I want to de-noise in order to run OCR on :

I am trying to read the 1973 from the image.

I have tried

import cv2,numpy as np

img=cv2.imread('uxWbP.png',0)
img = cv2.resize(img, (0, 0), fx=2, fy=2)
copy_img=np.copy(img)
#adaptive threshold as the image has different lighting conditions in different areas
thresh = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 21, 2)

contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
#kill small contours
for i_cnt, cnt in enumerate(sorted(contours, key=lambda x: cv2.boundingRect(x)[0])):
    _area = cv2.contourArea(cnt)
    x, y, w, h = cv2.boundingRect(cnt)
    x_y_area = w * h
    if 10000 < x_y_area and x_y_area < 400000:
        pass
        # cv2.rectangle(copy_img, (x, y), (x + w, y + h), (255, 0, 255), 2)
        # cv2.putText(copy_img, str(int(x_y_area)) + ' , ' + str(w) + ' , ' + str(h), (x, y + 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)
        # cv2.drawContours(copy_img, [cnt], 0, (0, 255, 0), 1)
    elif 10000 > x_y_area:
        #write over small contours
        cv2.drawContours(thresh, [cnt], -1, 255, -1)

cv2.imshow('img',copy_img)
cv2.imshow('thresh',thresh)
cv2.waitKey(0)

Which significantly improves the image to:

Any recommendations on how to filter this image sufficiently either on improvements to the filtered image or complete change from the start, that I could run OCR or some ML detection scripts on this? I'd like to split out the numbers for detection, but open to other methods as well.

Body:
Another thing to try - either separately from the blurring (or in combination with it - is the erosion/dilation game, as hinted at in the comment by @eldesgraciado , to whom I think a good part of the credit for these answers should go.

These two (erosion and dilation) can be applied one after the other, repeatedly. I think the trick is to change the kernel size. Anyway, I know I've used that to reduce noise in the past. Here's one example of dilation:

>>> import cv2
>>> import numpy as np
>>> im_0 = cv2.imread("FWM8b.png")
>>> k_size = 3
>>> kernel = np.ones((k_size, k_size), np.uint8)
>>> im_dilated = cv2.dilate(im_0, kernel, iterations=1)
>>> cv2.imshow("d", im_dilated)
>>> cv2.waitKey(0)

Make whatever kernel you want for erosion, and check out the effects.

>>> im_eroded = cv2.erode(im_0, kernel, iterations=1)
>>> cv2.imshow("erosion", im_eroded)
>>> cv2.waitKey(0)

Edit with possible improvements:

>>> im_blurred = cv2.GaussianBlur(im_dilated, (0, 0), 3)
>>> im_better = cv2.addWeighted(im_0, 0.5, im_blurred, 1.2, 0)
# Getting closer.

^ dilated, blurred, and combined (added) with original, 1st way

# Even better, I think.
im_better2 = cv2.addWeighted(im_0, 0.9, im_blurred, 1.7, 0)

^ dilated, blurred, and combined (added) with original, 2nd way

You could do artifact removal, but be careful not to get rid of the stalk of the 7. If you can keep the 7 together, you can do connected-component analysis and keep the biggest connected components.

You could sum the values of pixels on each column and each row, which would probably lead to something like this (very approximated - almost time for work). Note that I was much more careful with the green curve - sums of columns - but the consistency of scaling is probably off.

Note that this is more a sum of (255 - pixel_value). That could find you rectangles where your to-be-found glyphs (digits) should be. You could do a 2-d map of column_pixel_sum + row_pixel_sum, or just do some approximation, as I have done below.

Also to feel free to rotate the image (or take pixel sums at different angles), and combine your info for each rotation.

Lots of other things to try ... the suggestion by @eldesgraciado of a noise model is especially intriguing.

Another thing you could try out is to create a "noise model" and subtract it from the original image. First, take the image and apply Gaussian Blur with very low parameters, just barely blurring it, next subtract this mask from the image. From here, the steps are experimental: The difference should be again blurred and thresholded. Save this image. You run this pre-processing with various parameters and saving each time the final binary image, then, average the masks obtained so far. The persistent blobs should be the ones you are looking for... like some sort of spatial bandstop, I guess...

Keep experimenting.

Unsharp mask (my other answer) on this result image. More noise gone, but hurts the 7.


问:
How to programmatically check if FIPS is enabled on JVM
After Java 12, internal package com.sun.net.ssl is removed.
Is there any way that allow me to programmatically check if FIPS is enabled on JVM? </p>

答:
You can use java.security.Security class that centralize Security configurations and providers, and then check if a FIPS provider is registered.

Javadoc: Security

You can iterate over security providers and check if you have a FIPS provider, e.g. BouncyCastleFipsProvider or any other FIPS provider.

Also, You can check if you have the SunJSSE FIPS in compliant mode (SunPKCS11-NSS  provider). Bear in mind that the SunJSSE Fips compliant mode is being removed in JDK13 and as comments say, the provider is available until Java 13 but since Java 9 it probably won't work properly.  It is a point to consider and test.

Javadoc Provider: javadoc here).

For example:

```<code>Provider[] providers=Security.getProviders();
for (int i=0; i < providers.length;i++){
     if (providers[i].getName().contains(“Fips”)) return true;
}
</code>```

Hope it helps.

Body:
You can use java.security.Security class that centralize Security configurations and providers, and then check if a FIPS provider is registered.

Javadoc: Security

You can iterate over security providers and check if you have a FIPS provider, e.g. BouncyCastleFipsProvider or any other FIPS provider.

Also, You can check if you have the SunJSSE FIPS in compliant mode (SunPKCS11-NSS  provider). Bear in mind that the SunJSSE Fips compliant mode is being removed in JDK13 and as comments say, the provider is available until Java 13 but since Java 9 it probably won't work properly.  It is a point to consider and test.

Javadoc Provider: javadoc here).

For example:

Provider[] providers=Security.getProviders();
for (int i=0; i < providers.length;i++){
     if (providers[i].getName().contains(“Fips”)) return true;
}

Hope it helps.


问:
Is it posible to implement functions that use non blocking setTimeout synchronically?
I wonder if it is possible to call these 2 IIF synchronically that they produce at the end something like that?

```<code>######
#####
####
###
##
#
#
##
###
####
#####
###### ?
</code>```

the functions below do delayed console log. The idea is to console log with some delay row by row.

```<code> (function whileLoop(n) {
        setTimeout(function () {
            let hashArr = Array.apply(null, Array(n)).map(() => {
                return hashSymbol
            });
            console.log(hashArr);
            if (--n) whileLoop(n);
        }, 2000)
    })(6);

    (function whileLoop(n, m) {
        setTimeout(function () {
            let hashArr = Array.apply(null, Array(n)).map(() => {
                return hashSymbol
            });
            console.log(hashArr);
            if (n < m) {
                ++n;
                whileLoop(n, m);
            }
        }, 2000)
    })(1, 6);
</code>```

答:
You are almost there. I see that you understand that the recursive call to setTimeout emulates a while loop asynchronously. And I see that you understand how to decide when to continue the "loop" and when to stop:

```<code>if (--n) whileLoop(n);
</code>```

You just need to realize that the loop ends when the if condition is false. Thus, to run the second while loop just start it in the else:

```<code>if (--n) {
    whileLoop(n);
}
else {
    whileLoop2(1,6);
}
</code>```

There's a few repercussions of this:

The second whileLoop must be re-written to NOT be an IIFE - it must be a regular function called at the end of the first whileLoop as above.

You cannot reuse the name whileLoop for both functions. To differentiate the functions you must rename either the first or second "loop" functions.

This preserves your current logic requiring only 4 lines to be changed to get the behavior you want.

Body:
I wonder if it is possible to call these 2 IIF synchronically that they produce at the end something like that?

######
#####
####
###
##
#
#
##
###
####
#####
###### ?

the functions below do delayed console log. The idea is to console log with some delay row by row.

 (function whileLoop(n) {
        setTimeout(function () {
            let hashArr = Array.apply(null, Array(n)).map(() => {
                return hashSymbol
            });
            console.log(hashArr);
            if (--n) whileLoop(n);
        }, 2000)
    })(6);

    (function whileLoop(n, m) {
        setTimeout(function () {
            let hashArr = Array.apply(null, Array(n)).map(() => {
                return hashSymbol
            });
            console.log(hashArr);
            if (n < m) {
                ++n;
                whileLoop(n, m);
            }
        }, 2000)
    })(1, 6);

Body:
You are almost there. I see that you understand that the recursive call to setTimeout emulates a while loop asynchronously. And I see that you understand how to decide when to continue the "loop" and when to stop:

if (--n) whileLoop(n);

You just need to realize that the loop ends when the if condition is false. Thus, to run the second while loop just start it in the else:

if (--n) {
    whileLoop(n);
}
else {
    whileLoop2(1,6);
}

There's a few repercussions of this:

The second whileLoop must be re-written to NOT be an IIFE - it must be a regular function called at the end of the first whileLoop as above.

You cannot reuse the name whileLoop for both functions. To differentiate the functions you must rename either the first or second "loop" functions.

This preserves your current logic requiring only 4 lines to be changed to get the behavior you want.


问:
How to Solve App has Stopped in react native
after yarn or npm react-native-screens my app wont debug, it says unfortunatelly, App has stopped.

and when i did

```<code>react-native link react-native-screens
</code>```

it says

npm\react-native.ps1 cannot be loaded because running scripts is
  disabled on this system.

My RN vers.

react-native-cli: 2.0.1

react-native: 0.61.5

答:
That might be due to the blocker by execution policy on windows.

1) Open powershell

2) Check the results for

```<code>Get-ExecutionPolicy -List
</code>```

3) Set unrestricted

```<code>Set-ExecutionPolicy -Scope LocalMachine Unrestricted
</code>```

Body:
after yarn or npm react-native-screens my app wont debug, it says unfortunatelly, App has stopped.

and when i did

react-native link react-native-screens

it says

npm\react-native.ps1 cannot be loaded because running scripts is
  disabled on this system.

My RN vers.

react-native-cli: 2.0.1

react-native: 0.61.5

Body:
That might be due to the blocker by execution policy on windows.

1) Open powershell

2) Check the results for

Get-ExecutionPolicy -List

3) Set unrestricted

Set-ExecutionPolicy -Scope LocalMachine Unrestricted


问:
Shift DataFrame Columns Up Based on Threshold Value found in Columns
I have the following df:

```<code>                           testcol_45    testcol_76    testcol_99
dates
2020021918                 -1.33           -1.29           -1.38
2020022000                 -1.24           -1.33           -1.29
2020022006               -999.00           -1.23           -1.33
2020022012                 -0.88         -999.00           -1.21
2020022018                 -0.70           -0.88         -999.00
2020022100                 -0.46           -0.70           -0.89
2020022106                 -0.37           -0.45           -0.70
</code>```

I would like to shift the columns up, and not include the cells containing the -999 values once a -999 is reached for every column.

My desired result would look like the following:

```<code>                           testcol_45    testcol_76    testcol_99
dates
2020021918                 -0.88           -0.88           -0.89
2020022000                 -0.70           -1.70           -0.70
2020022006                 -0.46           -0.45
2020022012                 -0.37
2020022018
2020022100
2020022106
</code>```

(The length of column once this operation is achieved does not matter in this case; additionally the column names can be named anything so I cannot reference them by name).

I have tried various iterations of df.ffill and df.bfill, however to no avail.

Thank you for your time in advance.

答:
You can mask the top with nan and use the ideas in this question to shift the data. For example, you can mask with:

```<code>df.where(df.eq(-999)[::-1].cumsum().eq(0))
</code>```

Output:

```<code>            testcol_45  testcol_76  testcol_99
dates
2020021918         NaN         NaN         NaN
2020022000         NaN         NaN         NaN
2020022006         NaN         NaN         NaN
2020022012       -0.88         NaN         NaN
2020022018       -0.70       -0.88         NaN
2020022100       -0.46       -0.70       -0.89
2020022106       -0.37       -0.45       -0.70
</code>```

Body:
I have the following df:

                           testcol_45    testcol_76    testcol_99
dates
2020021918                 -1.33           -1.29           -1.38
2020022000                 -1.24           -1.33           -1.29
2020022006               -999.00           -1.23           -1.33
2020022012                 -0.88         -999.00           -1.21
2020022018                 -0.70           -0.88         -999.00
2020022100                 -0.46           -0.70           -0.89
2020022106                 -0.37           -0.45           -0.70

I would like to shift the columns up, and not include the cells containing the -999 values once a -999 is reached for every column.

My desired result would look like the following:

                           testcol_45    testcol_76    testcol_99
dates
2020021918                 -0.88           -0.88           -0.89
2020022000                 -0.70           -1.70           -0.70
2020022006                 -0.46           -0.45
2020022012                 -0.37
2020022018
2020022100
2020022106

(The length of column once this operation is achieved does not matter in this case; additionally the column names can be named anything so I cannot reference them by name).

I have tried various iterations of df.ffill and df.bfill, however to no avail.

Thank you for your time in advance.

Body:
You can mask the top with nan and use the ideas in this question to shift the data. For example, you can mask with:

df.where(df.eq(-999)[::-1].cumsum().eq(0))

Output:

            testcol_45  testcol_76  testcol_99
dates
2020021918         NaN         NaN         NaN
2020022000         NaN         NaN         NaN
2020022006         NaN         NaN         NaN
2020022012       -0.88         NaN         NaN
2020022018       -0.70       -0.88         NaN
2020022100       -0.46       -0.70       -0.89
2020022106       -0.37       -0.45       -0.70


问:
Passing Stream to a Funtion and Leaving it Open
I am having trouble writing to stream.  I think i understand why, but im not really following how to get around the issue.  Please see example code below

The requirement that the caller of Writer in the example below manages the stream, not the Writer.

this is example code in the caller:

```<code>using (Stream stream1 = new MemoryStream())
using (Stream stream2 = new FileStream("ex.txt", FileMode.Create))
{
    //example 1:
    Writer writer1 = new Writer();
    writer1.WriteToStream(stream1);

    //example 2:
    Writer writer2 = new Writer();
    writer2.WriteToStream(stream2);
}
</code>```

This is the Writer class:  its supposed to leave stream open after its done with it.

```<code>public class Writer
{
    public void WriteToStream(Stream destination)
    {
        Write(destination, "abc");
    }

    private void Write(Stream destination, string data)
    {
        Streamwriter sw = new StreamWriter(destination);
        sw.Write(data);
    }
}
</code>```

in this setup, nothing shows up in MemoryStream or "ex.txt".  I am guessing its because once you exit the Write method, StreamWriter is out of context, and stream goes with it before it gets a chance to be written to a file.

If I change the Write method to the example below, then i can get something to show up in the file, but the stream ends up closed, which goes against the requirement:

```<code>private void Write(Stream destination, string data)
{
    using(Streamwriter sw = new StreamWriter(destination))
    {
        sw.Write(data);
    }
}
</code>```

So, how do I write a string to a stream (Memory of File), without closing the stream in the process.  thank you

答:
You are missing Stream Flush.

Following will solve the issue:

```<code>private void Write(Stream destination, string data)
{
     var sw = new StreamWriter(destination);
     sw.Write(data);
     sw.Flush();
}
</code>```

However, open streams are notorious.

Body:
I am having trouble writing to stream.  I think i understand why, but im not really following how to get around the issue.  Please see example code below

The requirement that the caller of Writer in the example below manages the stream, not the Writer.

this is example code in the caller:

using (Stream stream1 = new MemoryStream())
using (Stream stream2 = new FileStream("ex.txt", FileMode.Create))
{
    //example 1:
    Writer writer1 = new Writer();
    writer1.WriteToStream(stream1);

    //example 2:
    Writer writer2 = new Writer();
    writer2.WriteToStream(stream2);
}

This is the Writer class:  its supposed to leave stream open after its done with it.

public class Writer
{
    public void WriteToStream(Stream destination)
    {
        Write(destination, "abc");
    }

    private void Write(Stream destination, string data)
    {
        Streamwriter sw = new StreamWriter(destination);
        sw.Write(data);
    }
}

in this setup, nothing shows up in MemoryStream or "ex.txt".  I am guessing its because once you exit the Write method, StreamWriter is out of context, and stream goes with it before it gets a chance to be written to a file.

If I change the Write method to the example below, then i can get something to show up in the file, but the stream ends up closed, which goes against the requirement:

private void Write(Stream destination, string data)
{
    using(Streamwriter sw = new StreamWriter(destination))
    {
        sw.Write(data);
    }
}

So, how do I write a string to a stream (Memory of File), without closing the stream in the process.  thank you

Body:
You are missing Stream Flush.

Following will solve the issue:

private void Write(Stream destination, string data)
{
     var sw = new StreamWriter(destination);
     sw.Write(data);
     sw.Flush();
}

However, open streams are notorious.


问:
In java selenium i am trying to send backspace character ('\uE003') or (\u0008) to a textbox to clear existing text
```<code>textboxElement.sendKeys("\uE003");
(or)
textboxElement.sendKeys("\u0008");

</code>```

But instead of removing the existing text in the textbox,   003 or 0008 is getting  added to the textbox. i cant use Keys.BACK_SPACE because it is not working on Ubuntu server.

答:
(1) first import selenium Keys to your class </p>

<p>(2) best way to clean/clear any input field through using length ,below method will delete/backspace
the all character in dynamic manner: </p>

```<code>public void clearText(WebDriver driver, WebElement element)
{
        String areaText = element.getText();
        int  lengthOfString = text.length();

        for(int i = 0 ; i < lengthOfString ; i++)
        {
            element.send_keys(Keys.BACKSPACE);
        }
}

or we can use below:

element.sendKeys(Keys.CONTROL + "a");
element.sendKeys(Keys.DELETE);

or

element.send_keys(Keys.CONTROL, 'a')
element.send_keys(Keys.BACKSPACE)
</code>```

Body:
textboxElement.sendKeys("\uE003");
(or)
textboxElement.sendKeys("\u0008");

But instead of removing the existing text in the textbox,   003 or 0008 is getting  added to the textbox. i cant use Keys.BACK_SPACE because it is not working on Ubuntu server.

Body:
(1) first import selenium Keys to your class

(2) best way to clean/clear any input field through using length ,below method will delete/backspace
the all character in dynamic manner:

public void clearText(WebDriver driver, WebElement element)
{
        String areaText = element.getText();
        int  lengthOfString = text.length();

        for(int i = 0 ; i < lengthOfString ; i++)
        {
            element.send_keys(Keys.BACKSPACE);
        }
}

or we can use below:

element.sendKeys(Keys.CONTROL + "a");
element.sendKeys(Keys.DELETE);

or

element.send_keys(Keys.CONTROL, 'a')
element.send_keys(Keys.BACKSPACE)


问:
default login url on HttpUnauthorizedResult in asp.net mvc
I have written a custom AuthorizeAttribute which has the following condition in asp.net mvc3 application:

```<code>public override void OnAuthorization(AuthorizationContext filterContext)
{
    //auth failed, redirect to Sign In
    if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
    {
       filterContext.Result = new HttpUnauthorizedResult();
    }
}
</code>```

And in my web.config, i have:

```<code><authentication mode="Forms">
  <forms loginUrl="~/User/SignIn" timeout="2880" />
</authentication>
</code>```

On authentication fail, it redirects to "/Account/Login" page by default.

How do i change this default redirect url and redirect it to "/User/SignIn"?

The screenshot shows the clear view of what i am trying to say..

Though i have set '/User/SignIn', it redirects to '/Account/Login'

答:
You should be modifying the root one for loginUrl.

i have created AuthorizationAttribute... it's redirecting properly
e.g.

```<code><authentication mode="Forms">
    <forms loginUrl="~/Authenticate/SignIn" timeout="2880"/>
</authentication>
</code>```

and my attribute is:

```<code>public class AuthorizationAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        base.OnAuthorization(filterContext);

        if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            filterContext.Result = new HttpUnauthorizedResult();
        }
    }
}
</code>```

and apply attribute to any method of your controller as necessary...

```<code>[AuthorizationAttribute()]
public ActionResult Index()
{
    return View();
}
</code>```

Body:
I have written a custom AuthorizeAttribute which has the following condition in asp.net mvc3 application:

public override void OnAuthorization(AuthorizationContext filterContext)
{
    //auth failed, redirect to Sign In
    if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
    {
       filterContext.Result = new HttpUnauthorizedResult();
    }
}

And in my web.config, i have:

<authentication mode="Forms">
  <forms loginUrl="~/User/SignIn" timeout="2880" />
</authentication>

On authentication fail, it redirects to "/Account/Login" page by default.

How do i change this default redirect url and redirect it to "/User/SignIn"?

The screenshot shows the clear view of what i am trying to say..

Though i have set '/User/SignIn', it redirects to '/Account/Login'

Body:
You should be modifying the root one for loginUrl.

i have created AuthorizationAttribute... it's redirecting properly
e.g.

<authentication mode="Forms">
    <forms loginUrl="~/Authenticate/SignIn" timeout="2880"/>
</authentication>

and my attribute is:

public class AuthorizationAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        base.OnAuthorization(filterContext);

        if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            filterContext.Result = new HttpUnauthorizedResult();
        }
    }
}

and apply attribute to any method of your controller as necessary...

[AuthorizationAttribute()]
public ActionResult Index()
{
    return View();
}


问:
How to get Full rows for groupby function for the following problem
Current Output

I am executing the following code to groupby similar items, take SUM and then average it with similar (groupby) items. The instruction works fine but i need my output with full rows, my current output provides only one item of ORIGIN_AIRPORT against all DESTINATION_AIRPORT. It should be ANC for SEA as well.
I hope anyone got my point.
df=df.groupby(['ORIGIN_AIRPORT', 'DESTINATION_AIRPORT']).agg({'SUM': np.average})

答:
IIUC try:

```<code>df=df.groupby(['ORIGIN_AIRPORT', 'DESTINATION_AIRPORT']).agg({'SUM': np.average}).reset_index()
</code>```

add reset_index() at the end of the query.

Body:
IIUC try:

df=df.groupby(['ORIGIN_AIRPORT', 'DESTINATION_AIRPORT']).agg({'SUM': np.average}).reset_index()

add reset_index() at the end of the query.


问:
Way to access stack top element to recursively compare if both stack elements are the same
How do I access the top elements of each stack so I can compare them? I used (iTop,i2Top,nTop,n2Top) because I've been testing to make this work but I can't seem to get the right output.
What am I doing wrong?

I assumed this would work, but it's not either. Basically I want to reference the top element of stack, and compare it to the top element of stack2. Then if they are equal, pop them and do the same for the rest of the stack. At the end, if the stack is empty because all elements were the same and got popped, then it's true the stacks are the same. And push back stack 1 and stack 2.
  Thank you

```<code>public Boolean sameStack(StackArray<E> s2) {
            E t1, t2;
            //E iTop = this.items[top];
            //E i2Top= s2.items[top];
            int nTop = this.top; //
            int n2Top= s2.top;  // nTop == n2Top is true even when elements are not equal
            boolean t = true;

            if(this.isEmpty() && s2.isEmpty()) {
                return t;
            }//if
            if(this.top != s2.top) {
                t = false;
                return t;
            }
            if(this.items[top] == s2.items[s2.top]){
                t1 = this.pop();
                t2 = s2.pop();
                t = sameStack(s2);
                push(t1);
                push(t2);
            }
            else{
                t = false;
            }
            return t;
}
</code>```

```<code>public class StackArray<E> {

        private int top=-1;
        private static final int MAX_ITEMS = 10;
        private E items[];

        @SuppressWarnings("unchecked")
        public StackArray() {
            items = (E[]) new Object[MAX_ITEMS];
            System.out.println("Stack Created!");
        }

        public void push(E e) {
            if (isFull()==true) {
            System.out.println("Stack Full!");
            }
            else{
                top=top+1;
                items[top] = e;
            }
        }//Push

        public E pop() {
            if (isEmpty()==true) {
                System.out.println("Stack Empty!");
                }
            else{
              E e = (E) items[top];
              items[top] = null;
              top = top-1;
              return e;
            }
            return null;
        } //pop

        public boolean isFull() {
            if (top == items.length-1) {
                return true;
            }
            return false;
        } //isFull

        public boolean isEmpty(){
            if (top==-1) {
                return true;
            }
            return false;
        }//isEmpty

        @Override
        public String toString()
        {
            System.out.println("Array:");
            System.out.print("{");
            for(int i = 0; i < items.length ;i++) {
                System.out.print(items[i]+" ");
        }
            System.out.print("}");
            return "";
        }//toString

        public Boolean sameStack(StackArray<E> s2) {
            E t1, t2;
            //E iTop = this.items[top];
            //E i2Top= s2.items[top];
            int nTop = this.top; //
            int n2Top= s2.top;  // nTop == n2Top is true even when elements are not equal
            boolean t = true;

            if(this.isEmpty() && s2.isEmpty()) {
                return t;
            }//if

            //This is the part I need to compare the elements
            if(nTop == n2Top) {
                t1 = this.pop()
                t2 = s2.pop();
//              t = sameStack(s2);
//              push(t1);
//              s2.push(t2);
            }
            return t;
        }

        public static void main(String[] args)
        {

            // Code reference for sameStack method
            StackArray<Integer> stack = new StackArray<Integer>();
            StackArray<Integer> stack2 = new StackArray<Integer>();

            stack.push(111);
            stack.push(222);
            stack.push(7177);
//          stack.push(40);
            stack2.push(444);
            stack2.push(555);
            stack2.push(777);
//          stack2.push(40);

            System.out.println(stack);
            System.out.println(stack2);

//          //Calling comparison method
            if (stack.sameStack(stack2) == true) {
                System.out.println("True, both stacks are equal.");
            }//if
            else {
                System.out.println("False, stacks are not equal.");
            }//else
            System.out.println(stack);
            System.out.println(stack2);
        }//main

}//class
</code>```

答:
If you specifically need to use recursion to test equality of your stacks then an easier method would be to pass the index to the method. Then you don't need to push and pop.

```<code>public boolean equals(Stack<E> other) {
    return equalsFrom(other, 0);
}

private boolean equalsFrom(Stack<E> other, int from) {
    if (from >= this.top || from >= other.top)
        return from >= this.top && from >= other.top;
    else
        return this.items[from].equals(other.items[from])
            && equalsFrom(other, from + 1);
}
</code>```

Hopefully that method makes sense to you. The first branch of the if statement could be read as "if I've reached the end of either stack then I must have reached the end of both stacks for them to be equal". the second branch could be read as "if I haven't reach the end of either stack then the current element must be equal and the rest of the stacks must be equal for the entire stacks to be equal".

Body:
How do I access the top elements of each stack so I can compare them? I used (iTop,i2Top,nTop,n2Top) because I've been testing to make this work but I can't seem to get the right output.
What am I doing wrong?

I assumed this would work, but it's not either. Basically I want to reference the top element of stack, and compare it to the top element of stack2. Then if they are equal, pop them and do the same for the rest of the stack. At the end, if the stack is empty because all elements were the same and got popped, then it's true the stacks are the same. And push back stack 1 and stack 2.
  Thank you

public Boolean sameStack(StackArray<E> s2) {
            E t1, t2;
            //E iTop = this.items[top];
            //E i2Top= s2.items[top];
            int nTop = this.top; //
            int n2Top= s2.top;  // nTop == n2Top is true even when elements are not equal
            boolean t = true;

            if(this.isEmpty() && s2.isEmpty()) {
                return t;
            }//if
            if(this.top != s2.top) {
                t = false;
                return t;
            }
            if(this.items[top] == s2.items[s2.top]){
                t1 = this.pop();
                t2 = s2.pop();
                t = sameStack(s2);
                push(t1);
                push(t2);
            }
            else{
                t = false;
            }
            return t;
}

public class StackArray<E> {

        private int top=-1;
        private static final int MAX_ITEMS = 10;
        private E items[];

        @SuppressWarnings("unchecked")
        public StackArray() {
            items = (E[]) new Object[MAX_ITEMS];
            System.out.println("Stack Created!");
        }

        public void push(E e) {
            if (isFull()==true) {
            System.out.println("Stack Full!");
            }
            else{
                top=top+1;
                items[top] = e;
            }
        }//Push

        public E pop() {
            if (isEmpty()==true) {
                System.out.println("Stack Empty!");
                }
            else{
              E e = (E) items[top];
              items[top] = null;
              top = top-1;
              return e;
            }
            return null;
        } //pop

        public boolean isFull() {
            if (top == items.length-1) {
                return true;
            }
            return false;
        } //isFull

        public boolean isEmpty(){
            if (top==-1) {
                return true;
            }
            return false;
        }//isEmpty

        @Override
        public String toString()
        {
            System.out.println("Array:");
            System.out.print("{");
            for(int i = 0; i < items.length ;i++) {
                System.out.print(items[i]+" ");
        }
            System.out.print("}");
            return "";
        }//toString

        public Boolean sameStack(StackArray<E> s2) {
            E t1, t2;
            //E iTop = this.items[top];
            //E i2Top= s2.items[top];
            int nTop = this.top; //
            int n2Top= s2.top;  // nTop == n2Top is true even when elements are not equal
            boolean t = true;

            if(this.isEmpty() && s2.isEmpty()) {
                return t;
            }//if

            //This is the part I need to compare the elements
            if(nTop == n2Top) {
                t1 = this.pop()
                t2 = s2.pop();
//              t = sameStack(s2);
//              push(t1);
//              s2.push(t2);
            }
            return t;
        }

        public static void main(String[] args)
        {

            // Code reference for sameStack method
            StackArray<Integer> stack = new StackArray<Integer>();
            StackArray<Integer> stack2 = new StackArray<Integer>();

            stack.push(111);
            stack.push(222);
            stack.push(7177);
//          stack.push(40);
            stack2.push(444);
            stack2.push(555);
            stack2.push(777);
//          stack2.push(40);

            System.out.println(stack);
            System.out.println(stack2);

//          //Calling comparison method
            if (stack.sameStack(stack2) == true) {
                System.out.println("True, both stacks are equal.");
            }//if
            else {
                System.out.println("False, stacks are not equal.");
            }//else
            System.out.println(stack);
            System.out.println(stack2);
        }//main

}//class

Body:
If you specifically need to use recursion to test equality of your stacks then an easier method would be to pass the index to the method. Then you don't need to push and pop.

public boolean equals(Stack<E> other) {
    return equalsFrom(other, 0);
}

private boolean equalsFrom(Stack<E> other, int from) {
    if (from >= this.top || from >= other.top)
        return from >= this.top && from >= other.top;
    else
        return this.items[from].equals(other.items[from])
            && equalsFrom(other, from + 1);
}

Hopefully that method makes sense to you. The first branch of the if statement could be read as "if I've reached the end of either stack then I must have reached the end of both stacks for them to be equal". the second branch could be read as "if I haven't reach the end of either stack then the current element must be equal and the rest of the stacks must be equal for the entire stacks to be equal".


问:
How is it possible to get duplicate keys in map
Sometimes my java/groovy application behaves strange: there is a map that is not null and has values in it, but when I'm trying to get value by exact same key that I see when I log that map I'm getting null. The most strange part is that map in log has duplicate keys.

Restarting application solves the problem, but I'm interested in how is that even possible.

I have this code:

```<code>def mainField = typeSettings?.mainField != null
    ? typeSettings?.mainField
    : classSettings.mainField
logger.info("${typeSettings}\n ${classSettings}\n ${classSettings.mainField}")
</code>```

I'm sure that classSettings is not null

And here's what I see in the log:

```<code>null
[
    iconsField:[],
    mainField:[
        [
            code:portalCard, showTitle:false, pages:[card]
        ],
        [
            code:portalAddForm, showTitle:false, pages:[addForm]
        ]
    ],
    footer:[showNegotDate:true, showPlanDate:true],
    footer:[showNegotDate:true, showPlanDate:true]
]
null
</code>```

But it's pretty clear that mainField is present in the map and even more there are somehow two duplicate keys footer in that map.

答: Seems like the problem is concurrent modification of that map which is mentioned here: What happens when two threads try to modify/access the same key in HashMap?</p>

Body:
Sometimes my java/groovy application behaves strange: there is a map that is not null and has values in it, but when I'm trying to get value by exact same key that I see when I log that map I'm getting null. The most strange part is that map in log has duplicate keys.

Restarting application solves the problem, but I'm interested in how is that even possible.

I have this code:

def mainField = typeSettings?.mainField != null
    ? typeSettings?.mainField
    : classSettings.mainField
logger.info("${typeSettings}\n ${classSettings}\n ${classSettings.mainField}")

I'm sure that classSettings is not null

And here's what I see in the log:

null
[
    iconsField:[],
    mainField:[
        [
            code:portalCard, showTitle:false, pages:[card]
        ],
        [
            code:portalAddForm, showTitle:false, pages:[addForm]
        ]
    ],
    footer:[showNegotDate:true, showPlanDate:true],
    footer:[showNegotDate:true, showPlanDate:true]
]
null

But it's pretty clear that mainField is present in the map and even more there are somehow two duplicate keys footer in that map.


问:
How to display one field from a JSON in node
I have this JSON file:

```<code>[
  {
    _id: 5e4b1213e666de6628044139,
    product: 'air-jordan-1-retro-high-unc-chicago-leather-w'
  },
  {
    _id: 5e4b121de666de662804413a,
    product: 'nike-air-force-1-high-just-don-blue'
  },
  {
    _id: 5e4b1227e666de662804413b,
    product: 'air-jordan-new-beginnings-pack-1-nike-air-ship'
  },
  {
    _id: 5e4b1246e666de662804413c,
    product: 'nike-sb-dunk-low-strangelove-skateboards'
  }
]
</code>```

I'd like to list all of the products all in one string. I noticed i can do docs[1].product but i want to do this for any amount.

I tried to do docs.product but the output is undefined

what i want is:

```<code>air-jordan-1-retro-high-unc-chicago-leather-w
nike-air-force-1-high-just-don-blue
air-jordan-new-beginnings-pack-1-nike-air-ship
nike-sb-dunk-low-strangelove-skateboards
</code>```

答:
Simple possible way could be:

```<code>let result = [
    {
        _id: '5e4b1213e666de6628044139',
        product: 'air-jordan-1-retro-high-unc-chicago-leather-w'
    },
    {
        _id: '5e4b121de666de662804413a',
        product: 'nike-air-force-1-high-just-don-blue'
    },
    {
        _id: '5e4b1227e666de662804413b',
        product: 'air-jordan-new-beginnings-pack-1-nike-air-ship'
    },
    {
        _id: '5e4b1246e666de662804413c',
        product: 'nike-sb-dunk-low-strangelove-skateboards'
    }
].map(t => t.product);

// result is an array so lets see what to do with it
console.log(result.join('\r\n'));
</code>```

Output:

```<code>> air-jordan-1-retro-high-unc-chicago-leather-w
> nike-air-force-1-high-just-don-blue
> air-jordan-new-beginnings-pack-1-nike-air-ship
> nike-sb-dunk-low-strangelove-skateboards
</code>```

Body:
I have this JSON file:

[
  {
    _id: 5e4b1213e666de6628044139,
    product: 'air-jordan-1-retro-high-unc-chicago-leather-w'
  },
  {
    _id: 5e4b121de666de662804413a,
    product: 'nike-air-force-1-high-just-don-blue'
  },
  {
    _id: 5e4b1227e666de662804413b,
    product: 'air-jordan-new-beginnings-pack-1-nike-air-ship'
  },
  {
    _id: 5e4b1246e666de662804413c,
    product: 'nike-sb-dunk-low-strangelove-skateboards'
  }
]

I'd like to list all of the products all in one string. I noticed i can do docs[1].product but i want to do this for any amount.

I tried to do docs.product but the output is undefined

what i want is:

air-jordan-1-retro-high-unc-chicago-leather-w
nike-air-force-1-high-just-don-blue
air-jordan-new-beginnings-pack-1-nike-air-ship
nike-sb-dunk-low-strangelove-skateboards

Body:
Simple possible way could be:

let result = [
    {
        _id: '5e4b1213e666de6628044139',
        product: 'air-jordan-1-retro-high-unc-chicago-leather-w'
    },
    {
        _id: '5e4b121de666de662804413a',
        product: 'nike-air-force-1-high-just-don-blue'
    },
    {
        _id: '5e4b1227e666de662804413b',
        product: 'air-jordan-new-beginnings-pack-1-nike-air-ship'
    },
    {
        _id: '5e4b1246e666de662804413c',
        product: 'nike-sb-dunk-low-strangelove-skateboards'
    }
].map(t => t.product);

// result is an array so lets see what to do with it
console.log(result.join('\r\n'));

Output:

> air-jordan-1-retro-high-unc-chicago-leather-w
> nike-air-force-1-high-just-don-blue
> air-jordan-new-beginnings-pack-1-nike-air-ship
> nike-sb-dunk-low-strangelove-skateboards


问:
Session attribute access and converting to int?
I have stored user id in Session using following command in Servlet:

```<code>HttpSession session = request.getSession();
session.setAttribute("user", user.getId());
</code>```

Now, I want to access that user id from another Servlet:

```<code>HttpSession session = request.getSession(false);
int userid = (int) session.getAttribute("user"); // This is not working

OR

User user = new User();
user.setId(session.getAttribute("user")); This ain't possible (Object != int)
</code>```

Question:

How can I cast to int and send the id to DAO for SELECT statement

答: Try int userid = (Integer) session.getAttribute("user");

Body:
I have stored user id in Session using following command in Servlet:

HttpSession session = request.getSession();
session.setAttribute("user", user.getId());

Now, I want to access that user id from another Servlet:

HttpSession session = request.getSession(false);
int userid = (int) session.getAttribute("user"); // This is not working

OR

User user = new User();
user.setId(session.getAttribute("user")); This ain't possible (Object != int)

Question:

How can I cast to int and send the id to DAO for SELECT statement


问:
Unable to restart production rails server when started as daemon
I am running a rails server on an Ubuntu EC2 instance and have run into an issue when it comes to deploying (and restarting) my server. The odd thing is; everything seems to work fine when I start a vanilla server (rails server), but when I start the server as a daemon it does not reset (rails server -d).

I use Capistrano to do deployment. As far as I can tell there is no issue; it pulls down my latest branch, runs migrations and does a touch tmp/restart.txt. I had tried making my tmp/restart.txt a shared file, but that does not seem to be the issue (although it is a configuration I think I'll keep). After discovering Capistrano is likely working as expected I tried sshing into the server and running touch tmp/restart.txt myself. It works for the vanilla server but not the daemon.

Has anyone seen this issue before? If there is more info I could provide please let me know!

Env:

ruby 2.6.3p62 @/home/deploy/.rvm/rubies/ruby-2.6.3/bin/ruby

Rails 5.2.3 @/home/deploy/.rvm/gems/ruby-2.6.3/bin/rails

Bundler version 2.1.2 @/home/deploy/.rvm/gems/ruby-2.6.3/bin/bundle

Node v13.8.0 @/home/deploy/.nvm/versions/node/v13.8.0/bin/node

My logs, tmp, and config/master.key are shared as part of my Capistrano setup.

答:
are you using puma or unicorn or passenger? apache or nginx? restarting the process depends more on that than anything.

personally, I like using Passenger with apache and when I restart apache, the passenger process restarts automatically.


问:
Is UITextField+UIPickerView supported under Mac Catalyst?
In my iOS app I have a textfield with a picker view assigned to it's inputView. On iOS devices the picker view pops up whenever the user taps the textfield. The same code does not do that, however, when I run it as a Mac/Catalyst app. My debug effort so far shows that the picker view methods are not called at all, so if the Mac requires additional textfield delegate methods to take focus away from the Mac's keyboard? Any idea how to make this work on a Mac? A barebones example code is below.</p>

```<code>class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {
@IBOutlet weak var myTextField: UITextField!

var myPickerView : UIPickerView!
var pickerData = ["Alpha" , "Bravo" , "Charlie" , "Delta"]

override func viewDidLoad() {
    super.viewDidLoad()

    self.myPickerView = UIPickerView(frame:CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 300))
    self.myPickerView.delegate = self
    self.myPickerView.dataSource = self

    self.myTextField.delegate = self
    self.myTextField.inputView = self.myPickerView

}

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return pickerData.count
 }
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return pickerData[row]
}
}
</code>```

答: It looks like a bug in Mac Catalyst. Try using the UIPicker embedded in an UIActionSheet. ActionSheetPicker-3.0 is a ready-made solution. Show the ActionSheetPicker in textFieldDidBeginEditing of your UITextField.

Body:
In my iOS app I have a textfield with a picker view assigned to it's inputView. On iOS devices the picker view pops up whenever the user taps the textfield. The same code does not do that, however, when I run it as a Mac/Catalyst app. My debug effort so far shows that the picker view methods are not called at all, so if the Mac requires additional textfield delegate methods to take focus away from the Mac's keyboard? Any idea how to make this work on a Mac? A barebones example code is below.

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {
@IBOutlet weak var myTextField: UITextField!

var myPickerView : UIPickerView!
var pickerData = ["Alpha" , "Bravo" , "Charlie" , "Delta"]

override func viewDidLoad() {
    super.viewDidLoad()

    self.myPickerView = UIPickerView(frame:CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 300))
    self.myPickerView.delegate = self
    self.myPickerView.dataSource = self

    self.myTextField.delegate = self
    self.myTextField.inputView = self.myPickerView

}

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return pickerData.count
 }
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return pickerData[row]
}
}