问:
Only last added notification gets triggered
I'm updating notification to the UNUserNotification framework for my alarm-like app, and I thought I succeeded, but I realized that when I set more than one alarm I only get notified the latest one. Repeating days are working the dough.
Could it be a problem of trigger identifier that is getting the same string as previous ones and overwrites it?
I really don't understand this behavior and I can't find where's the problem.

This is the code:

```<code>func setRouteNotification(_ date: Date, onWeekdaysForNotify weekdays:[Int], snoozeEnabled:Bool,  onSnooze: Bool, soundName: String, routeName: String, index: Int) {
    configureCategory()
    // Notification content
    let routeCheckNotificationContent = UNMutableNotificationContent()
    let datesForNotification = correctDate(date, onWeekdaysForNotify: weekdays)
    routeCheckNotificationContent.title = "Hello!! Are you ready to cycle?"
    routeCheckNotificationContent.body = "Check route for alerts?"
    routeCheckNotificationContent.categoryIdentifier = Id.notificationCategory
    routeCheckNotificationContent.sound = UNNotificationSound.init(named: soundName + ".mp3")

    let repeating: Bool = !weekdays.isEmpty
    routeCheckNotificationContent.userInfo = ["snooze" : snoozeEnabled, "index": index, "soundName": soundName, "routeName": routeName, "repeating" : repeating]
    //repeat weekly if repeat weekdays are selected
    //no repeat with snooze notification
    if !weekdays.isEmpty && !onSnooze{ }

    syncAlarmModel()
    var counter = 1

    for d in datesForNotification {
        if onSnooze {
            alarmModel.alarms[index].date = Scheduler.correctSecondComponent(date: alarmModel.alarms[index].date)
        } else {
            alarmModel.alarms[index].date = d
        }

        // Notification trigger
        let calendar = Calendar(identifier: .gregorian)
        let components = calendar.dateComponents(in: .current, from: d)
        let newComponents = DateComponents(calendar: calendar, timeZone: .current, month: components.month, day: components.day, hour: components.hour, minute: components.minute, second: components.second)
        let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: true)

        // Notification Request
        let routeNotificationRequest = UNNotificationRequest(identifier: "routeNotificationRequest\(scheduledNotifications.count + counter)", content: routeCheckNotificationContent, trigger: trigger)

        // Add request
        UNUserNotificationCenter.current().add(routeNotificationRequest) { (Error) in
            if Error != nil {
                print("something went wrong with adding notification")
            }
        }
        print("added request\(alarmModel.alarms.count + weekdays.count + counter)")
        scheduledNotifications.append(counter)
        print("scheduled notifications are \(scheduledNotifications.count)")
        counter = ( counter + 1 )
    }
    print(alarmModel.alarms)
}
</code>```

Any idea of why is not setting all the programmed notifications?
Thank you very much as usual.

EDIT:

I tried setting up an array var scheduledNotifications: [Int] = [] that stores a progressive number as notifications gets added, and use that as the identifier for the request

```<code>let routeNotificationRequest = UNNotificationRequest(identifier: "routeNotificationRequest\(scheduledNotifications.count + counter)", content: routeCheckNotificationContent, trigger: trigger)
</code>```

so I'm sure that all added notifications have a unique request identifier, but nothing changed, still gets notified only the latest one.

EDIT 2:
console output when I set 2 notification for everyday:

```<code>added request9B642AB7-D4F3-4BDA-A5B3-D259419390D5
scheduled notifications are 1
added requestBA0EF286-CD4D-408D-AEFC-E3DED24FBBB4
scheduled notifications are 2
added request947FEFEF-0B4E-4163-8435-DCEC725F21F7
scheduled notifications are 3
added request8FF19184-F970-45AD-95FE-39CFABF83348
scheduled notifications are 4
added requestA447CABF-AD80-4A73-B214-B8A1AA47F76B
scheduled notifications are 5
added request217EF2E4-6241-4840-9431-16744F2E5314
scheduled notifications are 6
added request28C92EF2-143C-4364-9CC3-EB5335AA9B6F
scheduled notifications are 7
[fix_it_mapView.Alarm(date: 2018-10-06 13:28:00 +0000, enabled: true, snoozeEnabled: false, repeatWeekdays: [1, 2, 3, 4, 5, 6, 7], uuid: "1C5A746F-F97D-4149-A0CC-47E6334BF3C3", mediaID: "", mediaLabel: "Burlone", label: "Route", onSnooze: false, routeLabel: "prova3"), fix_it_mapView.Alarm(date: 2018-09-23 13:29:00 +0000, enabled: true, snoozeEnabled: false, repeatWeekdays: [1, 2, 3, 4, 5, 6, 7], uuid: "B708BC27-82AA-4AA2-A8CA-252460E48476", mediaID: "", mediaLabel: "Burlone", label: "Route", onSnooze: false, routeLabel: "prova1")]
dates for notification are: [2018-09-30 13:28:00 +0000, 2018-10-01 13:28:00 +0000, 2018-10-02 13:28:00 +0000, 2018-10-03 13:28:00 +0000, 2018-10-04 13:28:00 +0000, 2018-10-05 13:28:00 +0000, 2018-10-06 13:28:00 +0000]
added request2467230C-BC4A-4307-A0FA-108C5C291DCC
scheduled notifications are 8
added requestF27D9E76-BCCC-4E3A-91D7-CA60E64B61B9
scheduled notifications are 9
added requestDFF37582-AB57-4029-A480-6FFA4068E316
scheduled notifications are 10
added requestBC5633BD-234C-4555-8259-988908B6E4DA
scheduled notifications are 11
added requestEC35384F-2E7F-4267-A745-777E0C2A2CE8
scheduled notifications are 12
added requestFF866674-ED94-4BA0-8BA5-E8314521EA4F
scheduled notifications are 13
added request4D739860-83CB-43F9-895D-2E8D48C5154E
scheduled notifications are 14
[fix_it_mapView.Alarm(date: 2018-10-06 13:28:00 +0000, enabled: true, snoozeEnabled: false, repeatWeekdays: [1, 2, 3, 4, 5, 6, 7], uuid: "1C5A746F-F97D-4149-A0CC-47E6334BF3C3", mediaID: "", mediaLabel: "Burlone", label: "Route", onSnooze: false, routeLabel: "prova3"), fix_it_mapView.Alarm(date: 2018-10-06 13:29:00 +0000, enabled: true, snoozeEnabled: false, repeatWeekdays: [1, 2, 3, 4, 5, 6, 7], uuid: "B708BC27-82AA-4AA2-A8CA-252460E48476", mediaID: "", mediaLabel: "Burlone", label: "Route", onSnooze: false, routeLabel: "prova1")]
dates for notification are: [2018-09-23 13:29:00 +0000, 2018-10-01 13:29:00 +0000, 2018-10-02 13:29:00 +0000, 2018-10-03 13:29:00 +0000, 2018-10-04 13:29:00 +0000, 2018-10-05 13:29:00 +0000, 2018-10-06 13:29:00 +0000]
2018-09-23 15:27:12.771112+0200 fix-it mapView[14162:297740] TIC Read Status [2:0x0]: 1:57
2018-09-23 15:27:12.771425+0200 fix-it mapView[14162:297740] TIC Read Status [2:0x0]: 1:57
</code>```

答:
I had the same problem and realized that it's happening because I was using the same identifier @"ID" for multiple notifications. When I made the identifiers unique, they were all triggered. </p>

```<code>UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"ID" content:notification trigger:trigger];
</code>```

Body:
I'm updating notification to the UNUserNotification framework for my alarm-like app, and I thought I succeeded, but I realized that when I set more than one alarm I only get notified the latest one. Repeating days are working the dough.
Could it be a problem of trigger identifier that is getting the same string as previous ones and overwrites it?
I really don't understand this behavior and I can't find where's the problem.

This is the code:

func setRouteNotification(_ date: Date, onWeekdaysForNotify weekdays:[Int], snoozeEnabled:Bool,  onSnooze: Bool, soundName: String, routeName: String, index: Int) {
    configureCategory()
    // Notification content
    let routeCheckNotificationContent = UNMutableNotificationContent()
    let datesForNotification = correctDate(date, onWeekdaysForNotify: weekdays)
    routeCheckNotificationContent.title = "Hello!! Are you ready to cycle?"
    routeCheckNotificationContent.body = "Check route for alerts?"
    routeCheckNotificationContent.categoryIdentifier = Id.notificationCategory
    routeCheckNotificationContent.sound = UNNotificationSound.init(named: soundName + ".mp3")

    let repeating: Bool = !weekdays.isEmpty
    routeCheckNotificationContent.userInfo = ["snooze" : snoozeEnabled, "index": index, "soundName": soundName, "routeName": routeName, "repeating" : repeating]
    //repeat weekly if repeat weekdays are selected
    //no repeat with snooze notification
    if !weekdays.isEmpty && !onSnooze{ }

    syncAlarmModel()
    var counter = 1

    for d in datesForNotification {
        if onSnooze {
            alarmModel.alarms[index].date = Scheduler.correctSecondComponent(date: alarmModel.alarms[index].date)
        } else {
            alarmModel.alarms[index].date = d
        }

        // Notification trigger
        let calendar = Calendar(identifier: .gregorian)
        let components = calendar.dateComponents(in: .current, from: d)
        let newComponents = DateComponents(calendar: calendar, timeZone: .current, month: components.month, day: components.day, hour: components.hour, minute: components.minute, second: components.second)
        let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: true)

        // Notification Request
        let routeNotificationRequest = UNNotificationRequest(identifier: "routeNotificationRequest\(scheduledNotifications.count + counter)", content: routeCheckNotificationContent, trigger: trigger)

        // Add request
        UNUserNotificationCenter.current().add(routeNotificationRequest) { (Error) in
            if Error != nil {
                print("something went wrong with adding notification")
            }
        }
        print("added request\(alarmModel.alarms.count + weekdays.count + counter)")
        scheduledNotifications.append(counter)
        print("scheduled notifications are \(scheduledNotifications.count)")
        counter = ( counter + 1 )
    }
    print(alarmModel.alarms)
}

Any idea of why is not setting all the programmed notifications?
Thank you very much as usual.

EDIT:

I tried setting up an array var scheduledNotifications: [Int] = [] that stores a progressive number as notifications gets added, and use that as the identifier for the request

let routeNotificationRequest = UNNotificationRequest(identifier: "routeNotificationRequest\(scheduledNotifications.count + counter)", content: routeCheckNotificationContent, trigger: trigger)

so I'm sure that all added notifications have a unique request identifier, but nothing changed, still gets notified only the latest one.

EDIT 2:
console output when I set 2 notification for everyday:

added request9B642AB7-D4F3-4BDA-A5B3-D259419390D5
scheduled notifications are 1
added requestBA0EF286-CD4D-408D-AEFC-E3DED24FBBB4
scheduled notifications are 2
added request947FEFEF-0B4E-4163-8435-DCEC725F21F7
scheduled notifications are 3
added request8FF19184-F970-45AD-95FE-39CFABF83348
scheduled notifications are 4
added requestA447CABF-AD80-4A73-B214-B8A1AA47F76B
scheduled notifications are 5
added request217EF2E4-6241-4840-9431-16744F2E5314
scheduled notifications are 6
added request28C92EF2-143C-4364-9CC3-EB5335AA9B6F
scheduled notifications are 7
[fix_it_mapView.Alarm(date: 2018-10-06 13:28:00 +0000, enabled: true, snoozeEnabled: false, repeatWeekdays: [1, 2, 3, 4, 5, 6, 7], uuid: "1C5A746F-F97D-4149-A0CC-47E6334BF3C3", mediaID: "", mediaLabel: "Burlone", label: "Route", onSnooze: false, routeLabel: "prova3"), fix_it_mapView.Alarm(date: 2018-09-23 13:29:00 +0000, enabled: true, snoozeEnabled: false, repeatWeekdays: [1, 2, 3, 4, 5, 6, 7], uuid: "B708BC27-82AA-4AA2-A8CA-252460E48476", mediaID: "", mediaLabel: "Burlone", label: "Route", onSnooze: false, routeLabel: "prova1")]
dates for notification are: [2018-09-30 13:28:00 +0000, 2018-10-01 13:28:00 +0000, 2018-10-02 13:28:00 +0000, 2018-10-03 13:28:00 +0000, 2018-10-04 13:28:00 +0000, 2018-10-05 13:28:00 +0000, 2018-10-06 13:28:00 +0000]
added request2467230C-BC4A-4307-A0FA-108C5C291DCC
scheduled notifications are 8
added requestF27D9E76-BCCC-4E3A-91D7-CA60E64B61B9
scheduled notifications are 9
added requestDFF37582-AB57-4029-A480-6FFA4068E316
scheduled notifications are 10
added requestBC5633BD-234C-4555-8259-988908B6E4DA
scheduled notifications are 11
added requestEC35384F-2E7F-4267-A745-777E0C2A2CE8
scheduled notifications are 12
added requestFF866674-ED94-4BA0-8BA5-E8314521EA4F
scheduled notifications are 13
added request4D739860-83CB-43F9-895D-2E8D48C5154E
scheduled notifications are 14
[fix_it_mapView.Alarm(date: 2018-10-06 13:28:00 +0000, enabled: true, snoozeEnabled: false, repeatWeekdays: [1, 2, 3, 4, 5, 6, 7], uuid: "1C5A746F-F97D-4149-A0CC-47E6334BF3C3", mediaID: "", mediaLabel: "Burlone", label: "Route", onSnooze: false, routeLabel: "prova3"), fix_it_mapView.Alarm(date: 2018-10-06 13:29:00 +0000, enabled: true, snoozeEnabled: false, repeatWeekdays: [1, 2, 3, 4, 5, 6, 7], uuid: "B708BC27-82AA-4AA2-A8CA-252460E48476", mediaID: "", mediaLabel: "Burlone", label: "Route", onSnooze: false, routeLabel: "prova1")]
dates for notification are: [2018-09-23 13:29:00 +0000, 2018-10-01 13:29:00 +0000, 2018-10-02 13:29:00 +0000, 2018-10-03 13:29:00 +0000, 2018-10-04 13:29:00 +0000, 2018-10-05 13:29:00 +0000, 2018-10-06 13:29:00 +0000]
2018-09-23 15:27:12.771112+0200 fix-it mapView[14162:297740] TIC Read Status [2:0x0]: 1:57
2018-09-23 15:27:12.771425+0200 fix-it mapView[14162:297740] TIC Read Status [2:0x0]: 1:57

Body:
I had the same problem and realized that it's happening because I was using the same identifier @"ID" for multiple notifications. When I made the identifiers unique, they were all triggered.

UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"ID" content:notification trigger:trigger];


来源: stackexchange

问:
RabbitMQ Mutual authentication using self signed certificates
I have religiously followed the instructions given at the RabbitMQ site to set up mutual authentication between a RabbitMQ server and a .Net client (using the official RabbitMQ client available at RabbitMQ.com)

https://www.rabbitmq.com/ssl.html

However, The instructions are missing a key point. For the peer certificate to be validated in the RabbitMQ server, A user needs to be mapped (for impersonation) to the peer certificate as described below

https://weblogs.asp.net/jeffreyabecker/Using-SSL-client-certificates-for-authentication-with-RabbitMQ

But, When the certificates are exchanged during a handshake, RabbitMQ server is looking for a username called 'O=client,CN=MyServer.com'  instead of 'CN=MyServer.com'

If I create this user with the required privileges, everything succeeds as expected.

I would like to know what is the reason for the unexpected 'O=client' part in the username. It is not documented anywhere in the RabbitMQ site.

Has anyone come across this?
What is the name of the user you have created for impersonating the peer/client?

Both RabbitMQ server and client versions are 3.6.5

Erlang version: 18

OS: Windows 10 Enterprise

答:
I have been looking at this recently and it is configurable on start up in docker by providing additional config as below

```<code>[
{rabbit, [
    {auth_mechanisms, ['EXTERNAL']},
    {loopback_users, []},
    {ssl_listeners, [5671]},
    {ssl_options, [{cacertfile, "etc/docker/certs.d/ca_certificate.pem"},
                {certfile,   "etc/docker/certs.d/server_certificate.pem"},
                {keyfile,    "etc/docker/certs.d/private_key.pem"},
                {verify,     verify_peer},
                {password,  ""},
                {fail_if_no_peer_cert, false}],
                {ssl_cert_login_from, common_name}}
]}
].
</code>```

The key here being the ssl_cert_login_from option allows you to use only the CN of the certificate

Removing this option enables the use of the DN

ContentLicense: CC BY-SA 3.0

Body:
I have been looking at this recently and it is configurable on start up in docker by providing additional config as below

[
{rabbit, [
    {auth_mechanisms, ['EXTERNAL']},
    {loopback_users, []},
    {ssl_listeners, [5671]},
    {ssl_options, [{cacertfile, "etc/docker/certs.d/ca_certificate.pem"},
                {certfile,   "etc/docker/certs.d/server_certificate.pem"},
                {keyfile,    "etc/docker/certs.d/private_key.pem"},
                {verify,     verify_peer},
                {password,  ""},
                {fail_if_no_peer_cert, false}],
                {ssl_cert_login_from, common_name}}
]}
].

The key here being the ssl_cert_login_from option allows you to use only the CN of the certificate

Removing this option enables the use of the DN

ContentLicense: CC BY-SA 4.0


问:
PayPal checkout: Don't allow creation of orders/subscriptions with only Client ID
I'm working on integrating PayPal Subscriptions into my web app. I create the subscriptions server-side, but it's trivial for anyone to create a subscription, since all PayPal requires is the public Client ID. This is intended to allow (mostly) server less transactions, but in my case it just feels like leaving part of my app exposed.

Is there any way to disable this?

答:
Continue to use the clientId+secret that you have on the server side (or, create a new pair and deactivate your current pair, if you are paranoid)

Then, create a separate permissionless REST app for use from your buttons. Make sure it corresponds to the same sandbox account if testing in sandbox, and give it the name "no permissions" for clarity. In the app features section, uncheck everything.

This new clientid will not be able to create orders or subscriptions, but can be used to present the buttons and approve ones that were created server-side.


答:
You can join the two dataframes by 'Location' and divide each column by Total.

```<code>library(dplyr)
df %>%
  left_join(total_df, by = 'Location') %>%
  mutate_at(vars(`Fourth Quintile`:`Third Quintile`), ~./Total)
</code>```

Title: I want to divide values in a cross tabulation based on one column by column in another dataframe in R

Body:
I have the cross tabulation below showing number of people that fall into each quintile for each location

                            Quintile
Location        Fourth Quintile Highest Quintile Lowest Quintile Second Quintile Third Quintile
  ACT          47926            56799           31146           28143          30494
  GA           117952            90323          106448          115168         125475
  GB           216805           204766          190530          195830         212645
  GD           17777            17707           10565           11362          13650
  GH           19393            14322           19122           19831          21443
  GM           403012           363902          385852          384362         396915
  GP           186868           256448          174139          165962         161256
  GS           432012           468749          399487          400870         411057
  NSW          192504           180875          218228          232050         217500
  NT           5759             5358            5151            4876           5279
  Qld          191812           192972          210659          222899         210492
  SA           25105            18248           32495           32662          30916
  Tas.         21130            14452           26584           27405          26695
  Vic.         111428            74023          131593          132609         126082
  WA           37837            60160           45700           43054          37517

I have another dataframe containing total number of people for each location.

Location Total
GS 2112175
NSW 1041157
GM 1934043
Vic  575735
GB 1020576
Qld 1028834
GA  555366
SA  139426
Perth  944673
WA  224268
GH   94111
Tas.  116266
GD   71061
NT   26423
ACT  194508

I want to divide the cross tab by the total for the corresponding location so the cross tab reflects a proportion/percentage of people in each quintile for each location.
So for example I would end up with Fourth quintile location ACT being 47926/194508 = 0.24... and do this for each.
How can I do this in R?

Body:
You can join the two dataframes by 'Location' and divide each column by Total.

library(dplyr)
df %>%
  left_join(total_df, by = 'Location') %>%
  mutate_at(vars(`Fourth Quintile`:`Third Quintile`), ~./Total)


问:
Java 7 underscore in numeric literals
When we must use a _ to separate digits in a number I don't understand the following case in which I can't use it:

In positions where a string of digits is expected

(as documented in the JDK7 guide here)

Some examples?

答:
My interpretation of this is that underscores cannot be placed by themselves in positions where a string of digits would normally be expected:

```<code>int x1= _; // Illegal.
</code>```

Title: Java 7 underscore in numeric literals

Body:
My interpretation of this is that underscores cannot be placed by themselves in positions where a string of digits would normally be expected:

int x1= _; // Illegal.


问:
Covert ISO Date String to x days/minutes ago
I want to convert a timestamp (e.g. 2020-05-01T07:28:02.657Z) to a timestamp that is 1 day or 1 minute prior.

Can someone help me fix this JavaScript function to get the desired output

```<code>aDay = '2020-05-01T07:28:02.657Z'
function timeSince(date) {

    var seconds = Math.floor((new Date() - date) / 1000);

    var interval = Math.floor(seconds / 31536000);

    if (interval > 1) {
      return interval + " years";
    }
    interval = Math.floor(seconds / 2592000);
    if (interval > 1) {
      return interval + " months";
    }
    interval = Math.floor(seconds / 86400);
    if (interval > 1) {
      return interval + " days";
    }
    interval = Math.floor(seconds / 3600);
    if (interval > 1) {
      return interval + " hours";
    }
    interval = Math.floor(seconds / 60);
    if (interval > 1) {
      return interval + " minutes";
    }
    return Math.floor(seconds) + " seconds";
  }
  console.log(timeSince(new Date(Date.now()- aDay)));
</code>```

答:
For 1 day ago

```<code>const asd = new Date('2020-05-01T07:28:02.657Z');
const dayDecreased = new Date('2020-05-01T07:28:02.657Z').setDate(asd.getDate() - 1);
new Date(dayDecreased).toUTCString() // utc added just for time zone, depend on you
</code>```

For 1 min ago

```<code>const asd = new Date('2020-05-01T07:28:02.657Z');
const minutesDecreased = new Date('2020-05-01T07:28:02.657Z').setMinutes(asd.getMinutes() - 1);
new Date(dayDecreased).toUTCString() // utc added just for time zone, depend on you

</code>```

As I check your above logic,
Dont try to perforn calculation when we have inbuild methods to do that work, if you want any specific functionality which cannot be provided by build in method, than its fine to do that

Body:
I want to convert a timestamp (e.g. 2020-05-01T07:28:02.657Z) to a timestamp that is 1 day or 1 minute prior.

Can someone help me fix this JavaScript function to get the desired output

aDay = '2020-05-01T07:28:02.657Z'
function timeSince(date) {

    var seconds = Math.floor((new Date() - date) / 1000);

    var interval = Math.floor(seconds / 31536000);

    if (interval > 1) {
      return interval + " years";
    }
    interval = Math.floor(seconds / 2592000);
    if (interval > 1) {
      return interval + " months";
    }
    interval = Math.floor(seconds / 86400);
    if (interval > 1) {
      return interval + " days";
    }
    interval = Math.floor(seconds / 3600);
    if (interval > 1) {
      return interval + " hours";
    }
    interval = Math.floor(seconds / 60);
    if (interval > 1) {
      return interval + " minutes";
    }
    return Math.floor(seconds) + " seconds";
  }
  console.log(timeSince(new Date(Date.now()- aDay)));

Body:
For 1 day ago

const asd = new Date('2020-05-01T07:28:02.657Z');
const dayDecreased = new Date('2020-05-01T07:28:02.657Z').setDate(asd.getDate() - 1);
new Date(dayDecreased).toUTCString() // utc added just for time zone, depend on you

For 1 min ago

const asd = new Date('2020-05-01T07:28:02.657Z');
const minutesDecreased = new Date('2020-05-01T07:28:02.657Z').setMinutes(asd.getMinutes() - 1);
new Date(dayDecreased).toUTCString() // utc added just for time zone, depend on you

As I check your above logic,
Dont try to perforn calculation when we have inbuild methods to do that work, if you want any specific functionality which cannot be provided by build in method, than its fine to do that


问:
can video/audio or other multimedia streaming work without an SSL certificate
I have an app which I have uploaded on the web now It is an E-learning application which requires video/audio or other multimedia streaming features e.g. It will have video chat and virtual classroom feature.

Now the thing is that I have heard from, someone, that If I don't have an SSL certificate on my website I won't be able to stream data online such as voice calls, virtual classroom, audio streams, etc.

答: Generally yes you should get an SSL certificate to live stream videos, audios, etc using WebRTC especially if your user uses Google Chrome then he won't be able to experience the full functionality of your product as google cares a lot about security.</p>


问:
Can you install command-line packages in jib docker image?
I need to install command line tools like jq, curl etc in the docker image created by maven jib plugin. How can I achieve this? Any help would be greatly appreciated. Thanks.</p>

答:
Adding a reference Dockerfile and you can build your own base image by creating your Dockerfile and then build it.

```<code>FROM openjdk:8-jdk-alpine

RUN apk add --no-cache curl tar bash procps

# Downloading and installing Maven
ARG MAVEN_VERSION=3.6.1
ARG USER_HOME_DIR="/root"
ARG SHA=b4880fb7a3d81edd190a029440cdf17f308621af68475a4fe976296e71ff4a4b546dd6d8a58aaafba334d309cc11e638c52808a4b0e818fc0fd544226d952544
ARG BASE_URL=https://apache.osuosl.org/maven/maven-3/${MAVEN_VERSION}/binaries

RUN mkdir -p /usr/share/maven /usr/share/maven/ref \
  && echo "Downlaoding maven" \
  && curl -fsSL -o /tmp/apache-maven.tar.gz ${BASE_URL}/apache-maven-${MAVEN_VERSION}-bin.tar.gz \
  \
  && echo "Checking download hash" \
  && echo "${SHA}  /tmp/apache-maven.tar.gz" | sha512sum -c - \
  \
  && echo "Unziping maven" \
  && tar -xzf /tmp/apache-maven.tar.gz -C /usr/share/maven --strip-components=1 \
  \
  && echo "Cleaning and setting links" \
  && rm -f /tmp/apache-maven.tar.gz \
  && ln -s /usr/share/maven/bin/mvn /usr/bin/mvn

ENV MAVEN_HOME /usr/share/maven
ENV MAVEN_CONFIG "$USER_HOME_DIR/.m2"

# Downloading and installing Gradle
# 1- Define a constant with the version of gradle you want to install
ARG GRADLE_VERSION=4.0.1

# 2- Define the URL where gradle can be downloaded from
ARG GRADLE_BASE_URL=https://services.gradle.org/distributions

# 3- Define the SHA key to validate the gradle download
#    obtained from here https://gradle.org/release-checksums/
ARG GRADLE_SHA=d717e46200d1359893f891dab047fdab98784143ac76861b53c50dbd03b44fd4

# 4- Create the directories, download gradle, validate the download, install it, remove downloaded file and set links
RUN mkdir -p /usr/share/gradle /usr/share/gradle/ref \
  && echo "Downlaoding gradle hash" \
  && curl -fsSL -o /tmp/gradle.zip ${GRADLE_BASE_URL}/gradle-${GRADLE_VERSION}-bin.zip \
  \
  && echo "Checking download hash" \
  && echo "${GRADLE_SHA}  /tmp/gradle.zip" | sha256sum -c - \
  \
  && echo "Unziping gradle" \
  && unzip -d /usr/share/gradle /tmp/gradle.zip \
   \
  && echo "Cleaning and setting links" \
  && rm -f /tmp/gradle.zip \
  && ln -s /usr/share/gradle/gradle-${GRADLE_VERSION} /usr/bin/gradle

# 5- Define environmental variables required by gradle
ENV GRADLE_VERSION 4.0.1
ENV GRADLE_HOME /usr/bin/gradle
ENV GRADLE_USER_HOME /cache

ENV PATH $PATH:$GRADLE_HOME/bin

VOLUME $GRADLE_USER_HOME

CMD [""]

</code>```

Ref:- https://docs.docker.com/engine/reference/builder/

Once your custom image is ready, push it to Registry and then reference it in jib in following manner.

```<code>mvn compile jib:build \
    -Djib.from.image=customImage
</code>```

Body:
Adding a reference Dockerfile and you can build your own base image by creating your Dockerfile and then build it.

FROM openjdk:8-jdk-alpine

RUN apk add --no-cache curl tar bash procps

# Downloading and installing Maven
ARG MAVEN_VERSION=3.6.1
ARG USER_HOME_DIR="/root"
ARG SHA=b4880fb7a3d81edd190a029440cdf17f308621af68475a4fe976296e71ff4a4b546dd6d8a58aaafba334d309cc11e638c52808a4b0e818fc0fd544226d952544
ARG BASE_URL=https://apache.osuosl.org/maven/maven-3/${MAVEN_VERSION}/binaries

RUN mkdir -p /usr/share/maven /usr/share/maven/ref \
  && echo "Downlaoding maven" \
  && curl -fsSL -o /tmp/apache-maven.tar.gz ${BASE_URL}/apache-maven-${MAVEN_VERSION}-bin.tar.gz \
  \
  && echo "Checking download hash" \
  && echo "${SHA}  /tmp/apache-maven.tar.gz" | sha512sum -c - \
  \
  && echo "Unziping maven" \
  && tar -xzf /tmp/apache-maven.tar.gz -C /usr/share/maven --strip-components=1 \
  \
  && echo "Cleaning and setting links" \
  && rm -f /tmp/apache-maven.tar.gz \
  && ln -s /usr/share/maven/bin/mvn /usr/bin/mvn

ENV MAVEN_HOME /usr/share/maven
ENV MAVEN_CONFIG "$USER_HOME_DIR/.m2"

# Downloading and installing Gradle
# 1- Define a constant with the version of gradle you want to install
ARG GRADLE_VERSION=4.0.1

# 2- Define the URL where gradle can be downloaded from
ARG GRADLE_BASE_URL=https://services.gradle.org/distributions

# 3- Define the SHA key to validate the gradle download
#    obtained from here https://gradle.org/release-checksums/
ARG GRADLE_SHA=d717e46200d1359893f891dab047fdab98784143ac76861b53c50dbd03b44fd4

# 4- Create the directories, download gradle, validate the download, install it, remove downloaded file and set links
RUN mkdir -p /usr/share/gradle /usr/share/gradle/ref \
  && echo "Downlaoding gradle hash" \
  && curl -fsSL -o /tmp/gradle.zip ${GRADLE_BASE_URL}/gradle-${GRADLE_VERSION}-bin.zip \
  \
  && echo "Checking download hash" \
  && echo "${GRADLE_SHA}  /tmp/gradle.zip" | sha256sum -c - \
  \
  && echo "Unziping gradle" \
  && unzip -d /usr/share/gradle /tmp/gradle.zip \
   \
  && echo "Cleaning and setting links" \
  && rm -f /tmp/gradle.zip \
  && ln -s /usr/share/gradle/gradle-${GRADLE_VERSION} /usr/bin/gradle

# 5- Define environmental variables required by gradle
ENV GRADLE_VERSION 4.0.1
ENV GRADLE_HOME /usr/bin/gradle
ENV GRADLE_USER_HOME /cache

ENV PATH $PATH:$GRADLE_HOME/bin

VOLUME $GRADLE_USER_HOME

CMD [""]

Ref:- https://docs.docker.com/engine/reference/builder/

Once your custom image is ready, push it to Registry and then reference it in jib in following manner.

mvn compile jib:build \
    -Djib.from.image=customImage


问:
Calling a stored procedure that returns a data set without DbSet
I have a stored procedure that returns a dataset without any primary key. The documentation states that you should call a stored procedure on the DbSet like:

```<code>var blogs = context.Blogs
    .FromSqlRaw("SELECT * FROM dbo.Blogs")
    .ToList();
</code>```

However I do not have a DB set. I can do something like:

```<code>await this.Database.ExecuteSqlRawAsync("[xxx].[VF_Set_PrimaryXXX] @BankDataId",param1);
</code>```

But this does not return data. So how do I call a stored procedure and return my own custom model in a list?

答:
I soved it like this:</p>

```<code>using (var db = new DB(_connStr))
{
    return db.Set<TeamMemberIteration>().FromSqlRaw("GetTeamMembersViewFromCurrentIteration").ToList();

}
</code>```

Body:
I have a stored procedure that returns a dataset without any primary key. The documentation states that you should call a stored procedure on the DbSet like:

var blogs = context.Blogs
    .FromSqlRaw("SELECT * FROM dbo.Blogs")
    .ToList();

However I do not have a DB set. I can do something like:

await this.Database.ExecuteSqlRawAsync("[xxx].[VF_Set_PrimaryXXX] @BankDataId",param1);

But this does not return data. So how do I call a stored procedure and return my own custom model in a list?

Body:
I soved it like this:

using (var db = new DB(_connStr))
{
    return db.Set<TeamMemberIteration>().FromSqlRaw("GetTeamMembersViewFromCurrentIteration").ToList();

}


问:
How to populate number for missing dates?
I have a table that look like this

```<code>date    counts
Sep-01   1
Sep-05   5
Sep-10   30
</code>```

As you can see the dates are jumping across and is not continuous. I want the final results to be populated for all calendar dates, and the value for the missing dates should be equal to the previous date. I played around with several SQL analytics functions but it doesn't seem to solve the problem. Any tips?

```<code>date    counts
Sep-01   1
Sep-02   1
Sep-03   1
Sep-04   1
Sep-05   5
Sep-06   5
Sep-07   5
Sep-08   5
Sep-09   5
Sep-10   30
Sep-11   30
...
</code>```

答:
Here is solution:

```<code>CREATE TABLE datadate(startdate DATETIME, cnt INT);

INSERT INTO datadate VALUES('2020-05-25',1);
INSERT INTO datadate VALUES('2020-05-27',2);
INSERT INTO datadate VALUES('2020-05-30',5);

SELECT * FROM datadate;

WITH RECURSIVE  cte_name (cnt,ddate) AS (
 SELECT cnt,MIN(startdate) AS ddate FROM datadate
           UNION ALL
           SELECT
           CASE
           WHEN (SELECT cnt FROM datadate WHERE startdate=DATE_ADD(ddate, INTERVAL 1 DAY)) IS NULL THEN cnt
           ELSE (SELECT cnt FROM datadate WHERE startdate=DATE_ADD(ddate, INTERVAL 1 DAY))
           END AS cnt,
           DATE_ADD(ddate, INTERVAL 1 DAY)
           FROM     cte_name
           WHERE    ddate < (SELECT MAX(startdate) FROM datadate)
)
SELECT * FROM cte_name;
</code>```

Input:

Output:

Body:
I have a table that look like this

date    counts
Sep-01   1
Sep-05   5
Sep-10   30

As you can see the dates are jumping across and is not continuous. I want the final results to be populated for all calendar dates, and the value for the missing dates should be equal to the previous date. I played around with several SQL analytics functions but it doesn't seem to solve the problem. Any tips?

date    counts
Sep-01   1
Sep-02   1
Sep-03   1
Sep-04   1
Sep-05   5
Sep-06   5
Sep-07   5
Sep-08   5
Sep-09   5
Sep-10   30
Sep-11   30
...

Body:
Here is solution:

CREATE TABLE datadate(startdate DATETIME, cnt INT);

INSERT INTO datadate VALUES('2020-05-25',1);
INSERT INTO datadate VALUES('2020-05-27',2);
INSERT INTO datadate VALUES('2020-05-30',5);

SELECT * FROM datadate;

WITH RECURSIVE  cte_name (cnt,ddate) AS (
 SELECT cnt,MIN(startdate) AS ddate FROM datadate
           UNION ALL
           SELECT
           CASE
           WHEN (SELECT cnt FROM datadate WHERE startdate=DATE_ADD(ddate, INTERVAL 1 DAY)) IS NULL THEN cnt
           ELSE (SELECT cnt FROM datadate WHERE startdate=DATE_ADD(ddate, INTERVAL 1 DAY))
           END AS cnt,
           DATE_ADD(ddate, INTERVAL 1 DAY)
           FROM     cte_name
           WHERE    ddate < (SELECT MAX(startdate) FROM datadate)
)
SELECT * FROM cte_name;

Input:

Output:


问:
Why can't I validate my Azaure AD JWT signature?
I have an application registered on my Azure AD tenant. When I receive the access token after logging in I send the token to my node.js API. I'm trying to validate the signature but I keep getting "invalid signature" error. The JWT header lists the specific key that it supposedly used to sign the token. So why can't I verify it? Is there something I need to tweak in the AAD configuration? Are there options I need to specify that I pass to azure-ad-jwt? I've tried passing in { audience: 'https://graph.windows.net'}. I've also tried passing in the audience that is in the decoded token as well as the specific kid that is listed in the header so that it only tries the specific key that the token says it is signed with.

This is my code that is giving me the error:

```<code>const aad = require('azure-ad-jwt');

module.exports = (req, res, next) => {
    const jwtToken = req.headers.authorization.replace('Bearer ', '');

    aad.verify(jwtToken, null, function (err, result) {
        if (result) {
            console.log("JWT is valid");
            next();
        } else {
            console.log("JWT is invalid: " + err);
            res.status(401).json({
                message: "Auth failed"
            });
        }
    });
};
</code>```

答:
If your front-end is acquiring a token for audience https://graph.windows.net, then that token is not meant for your API.
It is a token for Azure AD Graph API.
You should not be validating that.

Instead, your front-end needs to specify your API app's client id or app ID URI as the resource (if using the v1 endpoint/ADAL) or valid scopes defined by your API (if using the v2 endpoint/MSAL).
Then you will get a token you can validate.

Body:
I have an application registered on my Azure AD tenant. When I receive the access token after logging in I send the token to my node.js API. I'm trying to validate the signature but I keep getting "invalid signature" error. The JWT header lists the specific key that it supposedly used to sign the token. So why can't I verify it? Is there something I need to tweak in the AAD configuration? Are there options I need to specify that I pass to azure-ad-jwt? I've tried passing in { audience: 'https://graph.windows.net'}. I've also tried passing in the audience that is in the decoded token as well as the specific kid that is listed in the header so that it only tries the specific key that the token says it is signed with.

This is my code that is giving me the error:

const aad = require('azure-ad-jwt');

module.exports = (req, res, next) => {
    const jwtToken = req.headers.authorization.replace('Bearer ', '');

    aad.verify(jwtToken, null, function (err, result) {
        if (result) {
            console.log("JWT is valid");
            next();
        } else {
            console.log("JWT is invalid: " + err);
            res.status(401).json({
                message: "Auth failed"
            });
        }
    });
};


问:
LINQ-to-SQL - The null value cannot be assigned to a member with type
I have an issue with a LINQ query I am working on. This has worked perfect for a while, but we did a rollback of the database and now it doesn't work.

Basically, I'm inserting a new row into a table which has an autogenerating BigInt PK. But when SubmitChanges is called I get this error:

The null value cannot be assigned to a
  member with type System.Int64 which is
  a non-nullable value type

I've looked at the generated SQL, and the issue seems to likely revolve arond this after the insert:

SELECT CONVERT(BigInt,
  SCOPE_IDENTITY()) AS [value]

This seems to be returning null, but I have no idea why. Both the table and the LINQ dmbl are set up correctly for autogenerating PK's.

Any ideas?

EDIT: After some debugging, including trying an insert manually in SQL as someone kindly suggested, I've stumbled upon a very strange issue -

'Column or expression 'Outstanding' cannot be updated'

Outstanding is a non-nullable decimal(9,2) field

答:
Take a look at this thread - someone else had the same error as you, same situation. It turns out that there was an issue with running the actual insert, which resulted in no record being inserted. Then when SCOPE_IDENTITY() was called, it returned null, since no record was inserted.

Try running a straight Insert of the same values into the table through your Sql Management tool, and see if the row inserts properly. There might be some other issue that is preventing this (aside from the autogenerating PKs), which would be the root cause of the issue.


问:
Get the signed-in Office 365 user id
How can I get the signed-in Office 365 user's id in Excel VBA?

Not the the Application.Username or Environ("username")

答:
The Office extensibility model doesn't provide anything for that.

The best what you can do is to log in to the Outlook profile which corresponds to the Office account and use the GetExchangeUser method which returns an ExchangeUser object that represents the AddressEntry if the AddressEntry belongs to an Exchange AddressList object such as the Global Address List (GAL) and corresponds to an Exchange user. You have to be connected to the Exchange server to use this method. And nobody can guarantee the default profile is connected to the Office365 account in Outlook.

Title: Get the signed-in Office 365 user id


问:
Count the number of vowels and print them in a manner that string having more vowels come first
In,This code I've to "n" string. Then count the number of vowels in a string and print "n" number of string in a manner that a string having more vowels print first.

```<code>Sample Input:

3
My name
is
Paul Jonas

Sample Output:

Paul Jonas 4
My name 2
is 1
</code>```

This is my attempt but I'cant process the output that a string having more vowel comes first

```<code>import java.util.*;
public class CountVowel {
    public static void  main(String[] args){
        Scanner sc = new Scanner(System.in);
        ArrayList<String> word = new ArrayList<String>();

        int n;
        n = sc.nextInt();

        String str;

        sc.nextLine();
        for(int i=0;i<n;i++){
            str = sc.nextLine();
            word.add(str);
        }

        int arr[] = new int[3];
        int j = 0;
        for(String s:word){
            int count = 0;
            for(int i=0;i<s.length();i++){
                if(s.charAt(i)=='A' || s.charAt(i)=='E' || s.charAt(i)=='I' || s.charAt(i)=='O'||s.charAt(i)=='U'
                || s.charAt(i)=='a' || s.charAt(i)=='e' || s.charAt(i)=='i' || s.charAt(i)=='o' || s.charAt(i)=='u'){

                    count++;

                }
            }
            arr[j] = count;
            j++;

        }

        int i = 0;
        for(String s: word){

            System.out.println(s+" "+arr[i]);
            i++;
        }

    }
}
</code>```

So, I'm not getting my desired Output.

```<code>Input:

3
My name
is
Paul Jonas

Output I'm getting:

My name 2
is 1
Paul Jonas 4
</code>```

答: Youll need to sort this based on the occurrences of the vowel, i suggest using a hashmap in conjunction with Collections.sort so you get your desired output.

Body:
In,This code I've to "n" string. Then count the number of vowels in a string and print "n" number of string in a manner that a string having more vowels print first.

Sample Input:

3
My name
is
Paul Jonas

Sample Output:

Paul Jonas 4
My name 2
is 1

This is my attempt but I'cant process the output that a string having more vowel comes first

import java.util.*;
public class CountVowel {
    public static void  main(String[] args){
        Scanner sc = new Scanner(System.in);
        ArrayList<String> word = new ArrayList<String>();

        int n;
        n = sc.nextInt();

        String str;

        sc.nextLine();
        for(int i=0;i<n;i++){
            str = sc.nextLine();
            word.add(str);
        }

        int arr[] = new int[3];
        int j = 0;
        for(String s:word){
            int count = 0;
            for(int i=0;i<s.length();i++){
                if(s.charAt(i)=='A' || s.charAt(i)=='E' || s.charAt(i)=='I' || s.charAt(i)=='O'||s.charAt(i)=='U'
                || s.charAt(i)=='a' || s.charAt(i)=='e' || s.charAt(i)=='i' || s.charAt(i)=='o' || s.charAt(i)=='u'){

                    count++;

                }
            }
            arr[j] = count;
            j++;

        }

        int i = 0;
        for(String s: word){

            System.out.println(s+" "+arr[i]);
            i++;
        }

    }
}

So, I'm not getting my desired Output.

Input:

3
My name
is
Paul Jonas

Output I'm getting:

My name 2
is 1
Paul Jonas 4


问:
What is the effect of preserving Angular Router query parameters?
Per this article with Angular it's possible to preserve query parameters like this:

```<code>goUsers() {
  this.router.navigate(['/users'], { queryParamsHandling: 'preserve'
   });
}
</code>```

I'm looking for a practical examples that shows why we might want to do this?

答:
I'm using this to preserve the lang queryparam.

According to Google's guidelines, one url must match a specific content. So storing the language in localStorage is not recommended.

Body:
Per this article with Angular it's possible to preserve query parameters like this:

goUsers() {
  this.router.navigate(['/users'], { queryParamsHandling: 'preserve'
   });
}

I'm looking for a practical examples that shows why we might want to do this?


问:
Visual Studio Code: "Open with Live Server" and "Open with Default Browser" showing different web page
I was working on an html file using Live Server in Visual Studio Code. After I finished, When I opened it with the chrome, I found out all the elements are enlarged. I found out that "Open with Live Server" and "Open with Default Browser" option does not show the same element dimensions.

What I see using "Live Server"

What I see when I open it with default browser (chrome)

Why is this happening?
Is there any way to fix this dimension problem without having to write

答: I think you should try reloading the file from the default browser chrome because sometimes in chrome it happens that there is a problem and we don't get what we want. I have experienced this many times. So, my suggestion is to restart your computer or refreshing the site</p>


问:
cannot type 'e' or 'P' in MinGW/msys shells or terminals
I have successfully installed and used MinGW and msys in the past to compile and link Windows executables.  On a fresh installation for 32-bit Vista (the same platform as when I had previous success) I am getting some maddening behavior: when I type lower-case 'e' or upper-case 'P' in the provided shell environments I get an audible beep but no character!  Meaning I cannot type "make" or "echo" and then run those commands, for instance.  It goes: m-a-k-BEEP!

This no 'e' BEEPing occurs in the shell that opens when you invoke msys via the shortcut that gets generated by the installer, and in shells by navigating to c:\msys\1.0\bin and just double-clicking bash.exe, sh.exe, rxvt.exe (actually that has more of a muffled noise puff than a crisp BEEP), but always lower-case 'e' and capital 'P' will not echo to the terminal (or shell? obviously I don't have a handle on the differences between these terms).

I have tried the automated MinGW and msys installers, and a fresh manual install to the same end.

I do not understand shells very well, or how their environments evolve as they start up, so I don't know where to start looking for the source of this wacky behavior.

答:
In the directory C:\Documents and Settings\yourusername, you can find a file named '.bashrc'
add the following 2 lines
bind '"e":self-insert'
bind '"P":self-insert'

Dennis Williamson, Thank you very much! This problem bothering me for a long time.

ContentLicense: CC BY-SA 2.5


问:
Get type of properties unique to a child class
Is it possible to construct a TypeScript type that extracts the property names that are unique to a specific class, that it did not inherit from its parent class? For instance, this works if I know the parent class (Playground Link):

class Parent {
    hello = 'hello'
}

class Child extends Parent {
    world = 'world'
}

type OwnProps<Base, T extends Base> = Exclude<keyof T, keyof Base>

declare const ownProps: OwnProps<Parent, Child> // "world"
```

<p>However, I would like a way to accomplish the same type of thing, but without explicitly specifying the base class, something like this:</p>

<pre class="lang-js prettyprint-override"><code>type OwnProps<T, Base = T extends ???> = Exclude<keyof T, keyof Base>

declare const ownProps: OwnProps<Child> // "world"
</code>```

Is this possible? Is there some kind of conditional magic I can use in place of ??? that would let me infer types that the Child class extends?

答:
Unfortunately it looks impossible. TypeScript uses structural type system and a type doesn't store any information about class hierarchy, i.e. the Child type it's just { hello: string, world: string }.

You can also look at the other similar question: TypeScript: Get Type of Super Class?

Body:
Is it possible to construct a TypeScript type that extracts the property names that are unique to a specific class, that it did not inherit from its parent class? For instance, this works if I know the parent class (Playground Link):

class Parent {
    hello = 'hello'
}

class Child extends Parent {
    world = 'world'
}

type OwnProps<Base, T extends Base> = Exclude<keyof T, keyof Base>

declare const ownProps: OwnProps<Parent, Child> // "world"

However, I would like a way to accomplish the same type of thing, but without explicitly specifying the base class, something like this:

type OwnProps<T, Base = T extends ???> = Exclude<keyof T, keyof Base>

declare const ownProps: OwnProps<Child> // "world"

Is this possible? Is there some kind of conditional magic I can use in place of ??? that would let me infer types that the Child class extends?


问:
Azure Function Proxies that navigate to Angular 9 app on Azure Blob Storage result in mime type errors
I've hosted multiple Angular 9 apps on one Azure Blob Storage (see this question - credits to @Sam Erkiner). Now I want to navigate to one of these apps using Azure Function Proxies.
The config is as follows:

```<code>"proxyname": {
            "matchCondition": {
                "route": "/someroute"
            },
            "backendUri": "https://myazureblobstorage.z6.web.core.windows.net/folder/subfolder"
        }
</code>```

If I navigate to https://myazureblobstorage.z6.web.core.windows.net/folder/subfolder everything works fine.

If I navigate to https://myazurefunction.azurewebsites.net/someroute I receive several mime type error messages in the console and the screen remains white. I'm getting three error messages: "Loading module from 'link-to-js-file' was blocked because of a disallowed MIME type ("")"

What can I do to fix these errors and show the angular app? Thanks in advance.

Screenshots:

答:
```<code>Try this config :-

{
    "$schema": "http://json.schemastore.org/proxies",
    "proxies": {
        "root": {
            "matchCondition": {
                "route": "someRoute",
                "methods": [
                    "GET",
                    "HEAD"
                ]
            },
            "backendUri": "https://myazureblobstorage.z6.web.core.windows.net/subfolder/index.html",
            "responseOverrides": {
                "response.headers.Strict-Transport-Security": "max-age=31536000; includeSubDomains",
                "response.headers.X-Content-Type-Options": "nosniff",
                "response.headers.X-XSS-Protection": "1; mode=block",
                "response.headers.x-frame-options": "SAMEORIGIN",
                "response.headers.Content-Security-Policy": "default-src 'self'; script-src 'self' 'unsafe-eval'; style-src 'self' 'unsafe-inline';",
                "response.headers.Referrer-Policy": "same-origin",
                "response.headers.Feature-Policy": "payment 'self'; geolocation 'self'"
            }
        },
        "files": {
            "matchCondition": {
                "route": "someRoute/{filename}.{ext}",
                "methods": [
                    "GET",
                    "HEAD"
                ]
            },
            "backendUri": "https://myazureblobstorage.z6.web.core.windows.net/subfolder/{filename}.{ext}"
        },
        "routes": {
            "matchCondition": {
                "route": "someRoute/{*restOfPath}",
                "methods": [
                    "GET",
                    "HEAD"
                ]
            },
            "backendUri": "https://myazureblobstorage.z6.web.core.windows.net/subfolder/index.html",
            "responseOverrides": {
                "response.headers.Strict-Transport-Security": "max-age=31536000; includeSubDomains",
                "response.headers.X-Content-Type-Options": "nosniff",
                "response.headers.X-XSS-Protection": "1; mode=block",
                "response.headers.x-frame-options": "SAMEORIGIN",
                "response.headers.Content-Security-Policy": "default-src 'self'; script-src 'self' 'unsafe-eval'; style-src 'self' 'unsafe-inline';",
                "response.headers.Referrer-Policy": "same-origin",
                "response.headers.Feature-Policy": "payment 'self'; geolocation 'self'"
            }
        },
        "assets": {
            "matchCondition": {
                "route": "someRoute/assets/{file}",
                "methods": [
                    "GET",
                    "HEAD"
                ]
            },
            "backendUri": "https://myazureblobstorage.z6.web.core.windows.net/subfolder/assets/{file}"
        },
        "assets-folder-item": {
        "matchCondition": {
              "route": "my-center/assets/{folder}/{item}",
              "methods": [
                "GET",
                "HEAD"
            ]
         },
        "backendUri": "https://myazureblobstorage.z6.web.core.windows.net/folder/subfolder/assets/{folder}/{item}"
       }
    }
}
</code>```

Body:
I've hosted multiple Angular 9 apps on one Azure Blob Storage (see this question - credits to @Sam Erkiner). Now I want to navigate to one of these apps using Azure Function Proxies.
The config is as follows:

"proxyname": {
            "matchCondition": {
                "route": "/someroute"
            },
            "backendUri": "https://myazureblobstorage.z6.web.core.windows.net/folder/subfolder"
        }

If I navigate to https://myazureblobstorage.z6.web.core.windows.net/folder/subfolder everything works fine.

If I navigate to https://myazurefunction.azurewebsites.net/someroute I receive several mime type error messages in the console and the screen remains white. I'm getting three error messages: "Loading module from 'link-to-js-file' was blocked because of a disallowed MIME type ("")"

What can I do to fix these errors and show the angular app? Thanks in advance.

Screenshots:


问:
Using random enum to generate objects in java
There are four classes that interact with my project. The aim is to generate an object using enum, using the random values from enum.

The EthicalEngine class. I'll call the method from another class called ScenarioGenerator.

The Person class inherited from the Character abstract class.

I am not sure whether my method of initialization is correct or not. My idea is to initialize the instance of the Person in the ScenarioGenerator class, and use a method getRandomPerson() to call the constructor.

But I stuck, keep getting NullPointerException when I called the method.

Here is part of my Character class:

```<code>abstract class Character {

private int age;
private Gender gender;
private BodyType bodyType;
protected Profession profession;
protected AgeCategory ageCategory;
protected boolean isPregnant;

public enum Gender {
    MALE, FEMALE, UNKNOWN;
}

public enum BodyType {
    AVERAGE, ATHLETIC, OVERWEIGHT, UNSPECIFIED;
}

public enum Profession {
    DOCTOR, CEO, CRIMINAL, HOMELESS, UNEMPLOYED, MUSICIAN, BOXER ,UNKNOWN, NONE;
}

public Character(int age, Profession profession, Gender gender, BodyType bodyType, boolean isPregnant) {
    this.age = age;
    this.profession = profession;
    this.gender = gender;
    this.bodyType = bodyType;
    this.isPregnant = isPregnant;
}
</code>```

part of my Person class:

```<code>Person(int age, Profession profession ,Gender gender, BodyType bodyType, boolean isPregnant) {
    super(age, profession, gender, bodyType, isPregnant);
}
public Profession getProfession () { //use getter to generate a random value
    //only adults have profession
    if (getAge()<=16 || getAge()>68) {
        return Profession.NONE;
    } else {
        return Profession.values()[new Random().nextInt(Profession.values().length)];
    }
//other getters and setters
}
</code>```

Part of my ScenarioGenerator class:

public class ScenarioGenerator {

```<code>private Person person;
private Animal animal;
private Scenario scenario;
private Random random = new Random();

private int passengerCountMinimum;
private int passengerCountMaximum;

private int pedestrianCountMininum;
private int pedestrianCountMaximum;

public ScenarioGenerator() {
    random.setSeed(random.nextInt());
}

public ScenarioGenerator(long seed) {
    this.random = new Random(seed);
}

public Person getRandomPerson() {
    //need age, gender, bodyType, profession, pregnancy
    Person people = new Person(person.getAge(), person.getProfession(), person.getGender(),person.getBodyType(), person.isPregnant());
    return people;
}
</code>```

Part of my EthicalEngine class:

```<code>public class EthicalEngine {
    public static void main(String[] args) throws Exception {
    EthicalEngine ethicalEngine = new EthicalEngine();
    ScenarioGenerator scenarioGenerator = new ScenarioGenerator();
    scenarioGenerator.getRandomPerson();
}
</code>```

答:
you can generate random number and select all values

```<code>import java.util.Random;

public class ScenarioGenerator {

public Person getRandomPerson() {
    Random rand = new Random();

    // max age
    int age = rand.nextInt(100);

    // no of profession - 1
    int profession = rand.nextInt(8);

    // no of gender - 1
    int gender = rand.nextInt(2);

    // no of bodyType - 1
    int bodyType = rand.nextInt(3);

    int pragnency = rand.nextInt(2);

    //need age, gender, bodyType, profession, pregnancy
    Person people = new Person(age, Profession.values()[profession], Gender.values()[gender],BodyType.values()[bodyType], pragnency == 1 ? true : false);
    return people;
}
</code>```

}

Body:
There are four classes that interact with my project. The aim is to generate an object using enum, using the random values from enum.

The EthicalEngine class. I'll call the method from another class called ScenarioGenerator.

The Person class inherited from the Character abstract class.

I am not sure whether my method of initialization is correct or not. My idea is to initialize the instance of the Person in the ScenarioGenerator class, and use a method getRandomPerson() to call the constructor.

But I stuck, keep getting NullPointerException when I called the method.

Here is part of my Character class:

abstract class Character {

private int age;
private Gender gender;
private BodyType bodyType;
protected Profession profession;
protected AgeCategory ageCategory;
protected boolean isPregnant;

public enum Gender {
    MALE, FEMALE, UNKNOWN;
}

public enum BodyType {
    AVERAGE, ATHLETIC, OVERWEIGHT, UNSPECIFIED;
}

public enum Profession {
    DOCTOR, CEO, CRIMINAL, HOMELESS, UNEMPLOYED, MUSICIAN, BOXER ,UNKNOWN, NONE;
}

public Character(int age, Profession profession, Gender gender, BodyType bodyType, boolean isPregnant) {
    this.age = age;
    this.profession = profession;
    this.gender = gender;
    this.bodyType = bodyType;
    this.isPregnant = isPregnant;
}

part of my Person class:

Person(int age, Profession profession ,Gender gender, BodyType bodyType, boolean isPregnant) {
    super(age, profession, gender, bodyType, isPregnant);
}
public Profession getProfession () { //use getter to generate a random value
    //only adults have profession
    if (getAge()<=16 || getAge()>68) {
        return Profession.NONE;
    } else {
        return Profession.values()[new Random().nextInt(Profession.values().length)];
    }
//other getters and setters
}

Part of my ScenarioGenerator class:

public class ScenarioGenerator {

private Person person;
private Animal animal;
private Scenario scenario;
private Random random = new Random();

private int passengerCountMinimum;
private int passengerCountMaximum;

private int pedestrianCountMininum;
private int pedestrianCountMaximum;

public ScenarioGenerator() {
    random.setSeed(random.nextInt());
}

public ScenarioGenerator(long seed) {
    this.random = new Random(seed);
}

public Person getRandomPerson() {
    //need age, gender, bodyType, profession, pregnancy
    Person people = new Person(person.getAge(), person.getProfession(), person.getGender(),person.getBodyType(), person.isPregnant());
    return people;
}

Part of my EthicalEngine class:

public class EthicalEngine {
    public static void main(String[] args) throws Exception {
    EthicalEngine ethicalEngine = new EthicalEngine();
    ScenarioGenerator scenarioGenerator = new ScenarioGenerator();
    scenarioGenerator.getRandomPerson();
}

Body:
you can generate random number and select all values

import java.util.Random;

public class ScenarioGenerator {

public Person getRandomPerson() {
    Random rand = new Random();

    // max age
    int age = rand.nextInt(100);

    // no of profession - 1
    int profession = rand.nextInt(8);

    // no of gender - 1
    int gender = rand.nextInt(2);

    // no of bodyType - 1
    int bodyType = rand.nextInt(3);

    int pragnency = rand.nextInt(2);

    //need age, gender, bodyType, profession, pregnancy
    Person people = new Person(age, Profession.values()[profession], Gender.values()[gender],BodyType.values()[bodyType], pragnency == 1 ? true : false);
    return people;
}

}


问:
Are go modules meant to be installed as executable programs or packages?
Can Go modules be built as an executable program? Or, are they meant to be published as libraries for code reuse?</p>

答:
Building an executable and publishing a library are not mutually exclusive (note that modules are not compiled, packages are).

A module is a collection of related Go packages that are versioned together as a single unit.

Modules record precise dependency requirements and create reproducible builds.

https://github.com/golang/go/wiki/Modules#modules

Whether these packages contain a main package or not is irrelevant.


问:
Change the height of option tag from select
I have the next component:

 <Select
        mode="multiple"
        placeholder="Inserted are removed"
        value={selectedItems}
        onChange={this.handleChange}
        style={{ width: "100%" }}
      >
        {filteredOptions.map(item => (
          <Select.Option key={item} value={item}>
            {item}
          </Select.Option>
        ))}
 </Select>```
</div>
</div>

In my <strong>demo</strong>: https://codesandbox.io/s/hide-already-selected-ant-design-demo-39xfe?file=/index.js:542-889, i added some styles:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.ant-select-item-option-content {
  background-color: red;
}
.ant-select-item-option-active:not(.ant-select-item-option-disabled) {
  height: 10px;
  background-color: blue;
  height: auto;
}</code>```

Why  height:10px; does not work? And how to apply 10px of heigth for that selector?

答:
I checked your link. It seems like there is another style rule thats applying a min-height:32px; to the active element.

Either remove that or include min-height in your CSS like so:

```<code>.ant-select-item-option-active:not(.ant-select-item-option-disabled) {
  min-height: 10px;
  height: 10px;
  background-color: blue;
}
</code>```

Body:
I have the next component:

 <Select
        mode="multiple"
        placeholder="Inserted are removed"
        value={selectedItems}
        onChange={this.handleChange}
        style={{ width: "100%" }}
      >
        {filteredOptions.map(item => (
          <Select.Option key={item} value={item}>
            {item}
          </Select.Option>
        ))}
 </Select>

In my demo: https://codesandbox.io/s/hide-already-selected-ant-design-demo-39xfe?file=/index.js:542-889, i added some styles:

.ant-select-item-option-content {
  background-color: red;
}
.ant-select-item-option-active:not(.ant-select-item-option-disabled) {
  height: 10px;
  background-color: blue;
  height: auto;
}

Why  height:10px; does not work? And how to apply 10px of heigth for that selector?

Body:
I checked your link. It seems like there is another style rule thats applying a min-height:32px; to the active element.

Either remove that or include min-height in your CSS like so:

.ant-select-item-option-active:not(.ant-select-item-option-disabled) {
  min-height: 10px;
  height: 10px;
  background-color: blue;
}


问:
Continue in while inside foreach
In the following C# code snippet

I have a 'while' loop inside a 'foreach' loop and I wish to jump to the next item in 'foreach' when a certain condition occurs.

```<code>foreach (string objectName in this.ObjectNames)
{
    // Line to jump to when this.MoveToNextObject is true.
    this.ExecuteSomeCode();
    while (this.boolValue)
    {
        // 'continue' would jump to here.
        this.ExecuteSomeMoreCode();
        if (this.MoveToNextObject())
        {
            // What should go here to jump to next object.
        }
        this.ExecuteEvenMoreCode();
        this.boolValue = this.ResumeWhileLoop();
    }
    this.ExecuteSomeOtherCode();
}
</code>```

'continue' would jump to the beginning of the 'while' loop not the 'foreach' loop.
Is there's a keyword to use here, or should I just use goto which I don't really like.

答:
Use the break keyword. That will exit the while loop and continue execution outside it. Since you don't have anything after the while, it would loop around to the next item in the foreach loop.

Actually, looking at your example more closely, you actually want to be able to advance the for loop without exiting the while. You can't do this with a foreach loop, but you can break down a foreach loop to what it actually automates. In .NET, a foreach loop is actually rendered as a .GetEnumerator() call on the IEnumerable object (which your this.ObjectNames object is).

The foreach loop is basically this:

```<code>IEnumerator enumerator = this.ObjectNames.GetEnumerator();

while (enumerator.MoveNext())
{
    string objectName = (string)enumerator.Value;

    // your code inside the foreach loop would be here
}
</code>```

Once you have this structure, you can call enumerator.MoveNext() within your while loop to advance to the next element. So your code would become:

```<code>IEnumerator enumerator = this.ObjectNames.GetEnumerator();

while (enumerator.MoveNext())
{
    while (this.ResumeWhileLoop())
    {
        if (this.MoveToNextObject())
        {
            // advance the loop
            if (!enumerator.MoveNext())
                // if false, there are no more items, so exit
                return;
        }

        // do your stuff
    }
}
</code>```

OwnerDisplayName: Amr

Title: Continue in while inside foreach

Body:
In the following C# code snippet

I have a 'while' loop inside a 'foreach' loop and I wish to jump to the next item in 'foreach' when a certain condition occurs.

foreach (string objectName in this.ObjectNames)
{
    // Line to jump to when this.MoveToNextObject is true.
    this.ExecuteSomeCode();
    while (this.boolValue)
    {
        // 'continue' would jump to here.
        this.ExecuteSomeMoreCode();
        if (this.MoveToNextObject())
        {
            // What should go here to jump to next object.
        }
        this.ExecuteEvenMoreCode();
        this.boolValue = this.ResumeWhileLoop();
    }
    this.ExecuteSomeOtherCode();
}

'continue' would jump to the beginning of the 'while' loop not the 'foreach' loop.
Is there's a keyword to use here, or should I just use goto which I don't really like.

LastEditorDisplayName: configurator

Body:
Use the break keyword. That will exit the while loop and continue execution outside it. Since you don't have anything after the while, it would loop around to the next item in the foreach loop.

Actually, looking at your example more closely, you actually want to be able to advance the for loop without exiting the while. You can't do this with a foreach loop, but you can break down a foreach loop to what it actually automates. In .NET, a foreach loop is actually rendered as a .GetEnumerator() call on the IEnumerable object (which your this.ObjectNames object is).

The foreach loop is basically this:

IEnumerator enumerator = this.ObjectNames.GetEnumerator();

while (enumerator.MoveNext())
{
    string objectName = (string)enumerator.Value;

    // your code inside the foreach loop would be here
}

Once you have this structure, you can call enumerator.MoveNext() within your while loop to advance to the next element. So your code would become:

IEnumerator enumerator = this.ObjectNames.GetEnumerator();

while (enumerator.MoveNext())
{
    while (this.ResumeWhileLoop())
    {
        if (this.MoveToNextObject())
        {
            // advance the loop
            if (!enumerator.MoveNext())
                // if false, there are no more items, so exit
                return;
        }

        // do your stuff
    }
}

OwnerDisplayName: Chris Hynes

LastEditorDisplayName: Chris Hynes


问:
How to run multiple SQL queries?
I have a create table query, an update query ,and then drop table query. I need to run these three queries in one shot. What is the best way to do this?

```<code>Example
1st Query: Create table A.
2nd Query: Update value in table A
3rd Query: Drop table A.
</code>```

Instead of running these three queries one by one, I want to run them in on go either by PLSQL or some other way. Please help.

答:
Put the 3 queries following each other separated by a semi-colon:

```<code>SELECT *
FROM table_to_be_selected;
DROP TABLE the table_to_be_dropped;
TRUNCATE TABLE table_to_be_truncated;
</code>```

You can concatenate these queries in a string and execute that string.

Title: How to run multiple SQL queries?

Body:
I have a create table query, an update query ,and then drop table query. I need to run these three queries in one shot. What is the best way to do this?

Example
1st Query: Create table A.
2nd Query: Update value in table A
3rd Query: Drop table A.

Instead of running these three queries one by one, I want to run them in on go either by PLSQL or some other way. Please help.

Body:
Put the 3 queries following each other separated by a semi-colon:

SELECT *
FROM table_to_be_selected;
DROP TABLE the table_to_be_dropped;
TRUNCATE TABLE table_to_be_truncated;

You can concatenate these queries in a string and execute that string.


问:
How to connect Django ORM to mongo atlas?
I am trying to connect my django instance to a mongo db cluster using django. I have checked from various sources and the way it is getting closer to work is:

Install dnspython

Have the following DATABASES dict in settings.py

```<code>DATABASES = {
    'default': {
        'ENGINE': 'djongo',
        'NAME': 'test',
        'HOST': 'mongodb+srv://mongo_usr:' + urllib.parse.quote('mypassword') + '@domain_assigned.mongodb.net/test?ssl=true&ssl_cert_reqs=CERT_NONE&retryWrites=true',
        'ENFORCE_SCHEMA': False
    }
}

</code>```

It truly finds the endpoint but I am getting a weird error:

pymongo.errors.ServerSelectionTimeoutError: connection closed,connection closed,connection closed

has anyone fixed this before?

答:
Simplest and correct solution:

Step 1: Install djongo and dnspython

pip install djongo

pip install dnspython

Step 2: Changes in settings.py:

```<code>DATABASES = {
"default": {
    "ENGINE": "djongo",
    "CLIENT": {
        "host": "mongodb+srv://<username>:<password>@<cluster_name>.mongodb.net/?retryWrites=true&w=majority",
        "username": "<username>",
        "password": "<password>",
        "name": "<database_name>",
        "authMechanism": "SCRAM-SHA-1",
    },
}}
</code>```

Body:
I am trying to connect my django instance to a mongo db cluster using django. I have checked from various sources and the way it is getting closer to work is:

Install dnspython

Have the following DATABASES dict in settings.py

DATABASES = {
    'default': {
        'ENGINE': 'djongo',
        'NAME': 'test',
        'HOST': 'mongodb+srv://mongo_usr:' + urllib.parse.quote('mypassword') + '@domain_assigned.mongodb.net/test?ssl=true&ssl_cert_reqs=CERT_NONE&retryWrites=true',
        'ENFORCE_SCHEMA': False
    }
}

It truly finds the endpoint but I am getting a weird error:

pymongo.errors.ServerSelectionTimeoutError: connection closed,connection closed,connection closed

has anyone fixed this before?

Body:
Simplest and correct solution:

Step 1: Install djongo and dnspython

pip install djongo

pip install dnspython

Step 2: Changes in settings.py:

DATABASES = {
"default": {
    "ENGINE": "djongo",
    "CLIENT": {
        "host": "mongodb+srv://<username>:<password>@<cluster_name>.mongodb.net/?retryWrites=true&w=majority",
        "username": "<username>",
        "password": "<password>",
        "name": "<database_name>",
        "authMechanism": "SCRAM-SHA-1",
    },
}}


问:
Minikube connectex issue on Windows 10 Enterprise with Hyper-V
My laptop configuration: Windows 10 Enterprise with Hyper-V (rather than Virtual box).

I was following some Kubernetes tutorial and while doing so my internet connection went down for some time. Later, I resumed the learning but I got the following error and was not able to proceed:

```<code>C:\kubernetes\demo>minikube version
minikube version: v1.10.1
commit: 63ab801ac27e5742ae442ce36dff7877dcccb278

C:\kubernetes\demo>kubectl version --short
Client Version: v1.18.0
Server Version: v1.18.2

C:\kubernetes\demo>minikube ip
192.168.1.103
C:\kubernetes\demo>kubectl get all
Unable to connect to the server: dial tcp 192.168.1.103:8443: connectex: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
</code>```

Also, from the command: 'minikube logs', I see:

```<code>* E0529 17:56:11.077679       1 reflector.go:205] k8s.io/minikube/vendor/github.com/r2d4/external-storage/lib/controller/controller.go:412: Failed to list *v1.PersistentVolume: Get https://10.96.0.1:443/api/v1/persistentvolumes?resourceVersion=0: dial tcp 10.96.0.1:443: getsockopt: no route to host
* E0529 17:56:11.077719       1 reflector.go:205] k8s.io/minikube/vendor/github.com/r2d4/external-storage/lib/controller/controller.go:411: Failed to list *v1.PersistentVolumeClaim: Get https://10.96.0.1:443/api/v1/persistentvolumeclaims?resourceVersion=0: dial tcp 10.96.0.1:443: getsockopt: no route to host
</code>```

I did search on the google for this issue but eventually in vain.

Any pointers ?

Edit 1: This happens (as per my observation), when ever there is a change in network/internet (when I off/on VPN, example). Removal and ReInstall of minikube is not a feasible option all the time !

答:
I did run the below command and it is working fine until now.

```<code>minikube start --vm-driver hyperv
</code>```

previously, I was running the below command and ran into issue multiple times as discussed in question.

```<code>minikube start --vm-driver hyperv --hyperv-virtual-switch "Primary Virtual Switch"
</code>```

Here, I did create the "Primary Virtual Switch and probably this could be the potential virtual switch that was causing this issue.

Body:
My laptop configuration: Windows 10 Enterprise with Hyper-V (rather than Virtual box).

I was following some Kubernetes tutorial and while doing so my internet connection went down for some time. Later, I resumed the learning but I got the following error and was not able to proceed:

C:\kubernetes\demo>minikube version
minikube version: v1.10.1
commit: 63ab801ac27e5742ae442ce36dff7877dcccb278

C:\kubernetes\demo>kubectl version --short
Client Version: v1.18.0
Server Version: v1.18.2

C:\kubernetes\demo>minikube ip
192.168.1.103
C:\kubernetes\demo>kubectl get all
Unable to connect to the server: dial tcp 192.168.1.103:8443: connectex: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

Also, from the command: 'minikube logs', I see:

* E0529 17:56:11.077679       1 reflector.go:205] k8s.io/minikube/vendor/github.com/r2d4/external-storage/lib/controller/controller.go:412: Failed to list *v1.PersistentVolume: Get https://10.96.0.1:443/api/v1/persistentvolumes?resourceVersion=0: dial tcp 10.96.0.1:443: getsockopt: no route to host
* E0529 17:56:11.077719       1 reflector.go:205] k8s.io/minikube/vendor/github.com/r2d4/external-storage/lib/controller/controller.go:411: Failed to list *v1.PersistentVolumeClaim: Get https://10.96.0.1:443/api/v1/persistentvolumeclaims?resourceVersion=0: dial tcp 10.96.0.1:443: getsockopt: no route to host

I did search on the google for this issue but eventually in vain.

Any pointers ?

Edit 1: This happens (as per my observation), when ever there is a change in network/internet (when I off/on VPN, example). Removal and ReInstall of minikube is not a feasible option all the time !

Body:
I did run the below command and it is working fine until now.

minikube start --vm-driver hyperv

previously, I was running the below command and ran into issue multiple times as discussed in question.

minikube start --vm-driver hyperv --hyperv-virtual-switch "Primary Virtual Switch"

Here, I did create the "Primary Virtual Switch and probably this could be the potential virtual switch that was causing this issue.


问:
How to use variables in SQL raiserror
I am trying to show my int variables in raiserror @MaxAmount and @MinAmount

```<code>Raiserror('Total Amount should be less than %s and Greater than %s',16,1,@MaxAmount,@MinAmount)
</code>```

But Im getting error:

Must declare the scalar variable "@MaxAmount".

答:
The above solutions did not work for me, because you have to declare also severity and state. Without it the result will be like this:

Total Amount should be less than (null) and Greater than (null)

You can try this:

```<code>DECLARE @MaxAmount int = 16;
DECLARE @MinAmount int = 1;

Raiserror('Total Amount should be less than %d and Greater than %d', 16, 1, @MaxAmount, @MinAmount)
</code>```

Title: How to use variables in SQL raiserror

Body:
I am trying to show my int variables in raiserror @MaxAmount and @MinAmount

Raiserror('Total Amount should be less than %s and Greater than %s',16,1,@MaxAmount,@MinAmount)

But Im getting error:

Must declare the scalar variable "@MaxAmount".

Body:
The above solutions did not work for me, because you have to declare also severity and state. Without it the result will be like this:

Total Amount should be less than (null) and Greater than (null)

You can try this:

DECLARE @MaxAmount int = 16;
DECLARE @MinAmount int = 1;

Raiserror('Total Amount should be less than %d and Greater than %d', 16, 1, @MaxAmount, @MinAmount)


问:
Undefined index when clicking next page in laravel
Im doing function of search data and the result was in paginate . The paginate working for the first search but when i clicking next page or last page it return error like below

Undefined index: cu

Here is my code

pagination2.blade.php

```<code><div class="col-md-6 text-right text-center-xs">
        <ul class="pagination pagination-sm m-t-none m-b-none">
            @php
                if(isset($_GET["q"])){
                    $pg_url_param = url()->full() . "&page=";
                }else{
                    $pg_url_param = url()->current() . "?page=";
                }

                $pg_current = $paginationRecord->current_page;
                $pg_last = $paginationRecord->last_page;
            @endphp

        @if ($pg_current <= 1)
            <li><a type="button" class="first changePg disabled" name="first" id="firstPg" value=" Ι < " title="Click here to show first page records">«</a></li>
            <li><a type="button" class="previous changePg disabled" name="prev" id="previousPg" value=" << " title="Click here to show previous page records">‹</a></li>
        @else
            <li><a href="{{ $pg_url_param }}1" type="button" class="first changePg" name="first" id="firstPg" value=" Ι < " title="Click here to show first page records">«</a></li>
            <li><a href="{{ $pg_url_param . ($pg_current - 1) }}" type="button" class="previous changePg" name="prev" id="previousPg" value=" << " title="Click here to show previous page records">‹</a></li>
        @endif

            <li><input class="" type="text" name="paginationPgNo" id="paginationPgNo" readonly="readonly" value="{{ $pg_current }} of {{ $pg_last }}" /></li>

        @if ($pg_current >= $pg_last)
            <li><a type="button" class="next changePg disabled" name="next" id="nextPg" value=" >> " title="Click here to show next page records">›</a></li>
            <li><a type="button" class="last changePg disabled" name="last" id="lastPg" value=" > Ι " title="Click here to show last page records">»</a></li>
        @else
            <li><a href="{{ $pg_url_param . ($pg_current + 1) }}" type="button" class="next changePg" name="next" id="nextPg" value=" >> " title="Click here to show next page records">›</a></li>
            <li><a href="{{ $pg_url_param . $pg_last }}" type="button" class="last changePg" name="last" id="lastPg" value=" > Ι " title="Click here to show last page records">»</a></li>
        @endif
        </ul>
    </div>

</code>```

my view blade which is already contain cu index

```<code> <div class="col-md-6 form-group">
                        <label for="sm" class="control-label">{{ __('messages.module.customer') }}</label>
                        <select class="input-sm form-control" name="cu" id="cu" >
                            @if(request()->session()->get('loginrole') == 'L04')
                            @if(!empty($content->custUserList))
                            @foreach($content->custUserList as $custuser)

                            @if(isset($custuser->irel__h_d_customer_master))
                            @if($custuser->rcu_customer_id ==   $custuser->irel__h_d_customer_master->cu_customer_ID)
                            <option value="{{  $custuser->irel__h_d_customer_master->cu_customer_ID }}">{{  $custuser->irel__h_d_customer_master->cu_customer_Shortname}} - {{  $custuser->irel__h_d_customer_master->cu_customer_Name }}</option>
                            @endif
                            @endif

                            @endforeach
                            @endif
                            @else
                            <option value="">{{ __('messages.select') }}</option>
                            @if(!empty($content->custUserList))
                            @foreach($content->custUserList as $custuser)

                            @if(isset($custuser->irel__h_d_customer_master))
                            @if($custuser->rcu_customer_id ==   $custuser->irel__h_d_customer_master->cu_customer_ID)
                            <option value="{{  $custuser->irel__h_d_customer_master->cu_customer_ID }}">{{  $custuser->irel__h_d_customer_master->cu_customer_Shortname}} - {{  $custuser->irel__h_d_customer_master->cu_customer_Name }}</option>
                            @endif
                            @endif

                            @endforeach
                            @endif
                            @endif
                        </select>
                    </div>

</code>```

my Controller

```<code>public function searchIncident(Request $request){

 if(isset($_GET["page"])) {
            $g_page = "?page=" . filter_var($_GET["page"], FILTER_SANITIZE_STRING);
        } else {
            $g_page = null;
        }

       // dd($g_page);

        $cust = filter_var($_GET["cu"], FILTER_SANITIZE_STRING);
        $customer = explode(' ',$cust);
        $branch = filter_var($_GET["br"], FILTER_SANITIZE_STRING);
        $category = filter_var($_GET["ct"], FILTER_SANITIZE_STRING);
        $pciisms = ['PCI','ISMS']  ;
        //dd($pciisms);
        $state = filter_var($_GET["stt"], FILTER_SANITIZE_STRING);
        $severity = filter_var($_GET["sv"], FILTER_SANITIZE_STRING);
        $logno = filter_var($_GET["cm"], FILTER_SANITIZE_STRING);
        $status = filter_var($_GET["st"], FILTER_SANITIZE_STRING);
        $group = filter_var($_GET["gr"], FILTER_SANITIZE_STRING);
        $createdby = filter_var($_GET["crtedBy"], FILTER_SANITIZE_STRING);
        $vendor = filter_var($_GET["ven"], FILTER_SANITIZE_STRING);
        $vendorrptno = filter_var($_GET["rptno"], FILTER_SANITIZE_STRING);
        $datefrom = filter_var($_GET["dtFrom"], FILTER_SANITIZE_STRING);
        $dateto = filter_var($_GET["dtTo"], FILTER_SANITIZE_STRING);
        $clsddatefrom = filter_var($_GET["dtClosedFrom"], FILTER_SANITIZE_STRING);
        $clsddateto = filter_var($_GET["dtClosedTo"], FILTER_SANITIZE_STRING);
        $probtype = filter_var($_GET["JpnProbType"], FILTER_SANITIZE_STRING);
        $caller = filter_var($_GET["callerName"], FILTER_SANITIZE_STRING);
        $person = filter_var($_GET["personName"], FILTER_SANITIZE_STRING);
        $custrptno = filter_var($_GET["cuRpt"], FILTER_SANITIZE_STRING);
        $assetsn = filter_var($_GET["assetSN"], FILTER_SANITIZE_STRING);
        $supplier = filter_var($_GET["sup"], FILTER_SANITIZE_STRING);
        $receivedby = filter_var($_GET["rcvdBy"], FILTER_SANITIZE_STRING);
        $closedby = filter_var($_GET["clsdBy"], FILTER_SANITIZE_STRING);

        $options = [
            'headers' => [
                'Content-Type' => 'application/json',
                'Accept' => 'application/json',
            ],
            'json' => [
                'customer' => $customer,
                'branch' => $branch,
                'category' => $category,
                'pciisms' => $pciisms,
                'state' => $state,
                'severity' => $severity,
                'logno' => $logno,
                'status' => $status,
                'group' => $group,
                'createdby' => $createdby,
                'vendor' => $vendor,
                'vendorrptno' => $vendorrptno,
                'datefrom' => $datefrom,
                'dateto' => $dateto,
                'clsddatefrom' => $clsddatefrom,
                'clsddateto' => $clsddateto,
                'probtype' => $probtype,
                'caller' => $caller,
                'person' => $person,
                'custrptno' => $custrptno,
                'assetsn' => $assetsn,
                'supplier' => $supplier,
                'receivedby' => $receivedby,
                'closedby' => $closedby,

            ],
        ];

        $response =  $this->client->post('searchIncident'.$g_page, $options)->getBody();
        $content = json_decode($response->getContents());
        $paginationRecord = $content->data->incidentList ;

        return view('incident.HDCaseMasterList', compact('paginationRecord'));

}

</code>```

All data was set 15 per page . The data was pull from backend project. I expect all the data was shown on the next page. Hope its help and sorry for my english

答:
Your undefined index is occurring here:

```<code>$cust = filter_var($_GET["cu"], FILTER_SANITIZE_STRING);
</code>```

The quickest/easiest solution here (for the specific problem being asked about here, which is the problem of the undefined index error), would be to either (1) actually define it beforehand (not really best practise in this particular case, given we're talking about an index of $_GET; the reasons for my saying this being a little outside the scope of the question, so moving on..), or (2) just guard/check for the existence of it beforehand (the better of these two mentioned solutions).

Example of solution 1:

```<code>if (!isset($_GET["cu"])) {
    $_GET["cu"] = '';
}
$cust = filter_var($_GET["cu"], FILTER_SANITIZE_STRING);
</code>```

Example of solution 2 (using fully-formed if/else; most verbose; may be more/less preferred, depending on code-style preferences):

```<code>if (isset($_GET["cu"])) {
    $cust = filter_var($_GET["cu"], FILTER_SANITIZE_STRING);
} else {
    $cust = "";
}
</code>```

Example of solution 2 (using ternary; less verbose; may be more/less preferred, depending on code-style preferences):

```<code>$cust = filter_var(isset($_GET["cu"]) ? $_GET["cu"] : "", FILTER_SANITIZE_STRING);
</code>```

Example of solution 2 (using null coalescence; least verbose; may be more/less preferred, depending on code-style preferences; best if targeting PHP versions >= 7 only; won't work if support for PHP < 7 is required for your project):

```<code>$cust = filter_var($_GET["cu"] ?? "", FILTER_SANITIZE_STRING);
</code>```

Note: My reply is specifically addressing only the undefined index error. I haven't tested or audited your code, so whether there are other problems, or other things that need addressing, I wouldn't yet know.

Body:
Im doing function of search data and the result was in paginate . The paginate working for the first search but when i clicking next page or last page it return error like below

Undefined index: cu

Here is my code

pagination2.blade.php

            @php
                if(isset($_GET["q"])){
                    $pg_url_param = url()->full() . "&page=";
                }else{
                    $pg_url_param = url()->current() . "?page=";
                }

                $pg_current = $paginationRecord->current_page;
                $pg_last = $paginationRecord->last_page;
            @endphp

        @if ($pg_current <= 1)

<a type="button" class="first changePg disabled" name="first" id="firstPg" value=" Ι < " title="Click here to show first page records">«

<a type="button" class="previous changePg disabled" name="prev" id="previousPg" value=" << " title="Click here to show previous page records">‹

        @else

<a href="{{ $pg_url_param }}1" type="button" class="first changePg" name="first" id="firstPg" value=" Ι < " title="Click here to show first page records">«

<a href="{{ $pg_url_param . ($pg_current - 1) }}" type="button" class="previous changePg" name="prev" id="previousPg" value=" << " title="Click here to show previous page records">‹

        @endif

<input class="" type="text" name="paginationPgNo" id="paginationPgNo" readonly="readonly" value="{{ $pg_current }} of {{ $pg_last }}" />

        @if ($pg_current >= $pg_last)

> " title="Click here to show next page records">›

 Ι " title="Click here to show last page records">»

        @else

> " title="Click here to show next page records">›

 Ι " title="Click here to show last page records">»

        @endif

my view blade which is already contain cu index

                        {{ __('messages.module.customer') }}
                        <select class="input-sm form-control" name="cu" id="cu" >
                            @if(request()->session()->get('loginrole') == 'L04')
                            @if(!empty($content->custUserList))
                            @foreach($content->custUserList as $custuser)

                            @if(isset($custuser->irel__h_d_customer_master))
                            @if($custuser->rcu_customer_id ==   $custuser->irel__h_d_customer_master->cu_customer_ID)
                            <option value="{{  $custuser->irel__h_d_customer_master->cu_customer_ID }}">{{  $custuser->irel__h_d_customer_master->cu_customer_Shortname}} - {{  $custuser->irel__h_d_customer_master->cu_customer_Name }}</option>
                            @endif
                            @endif

                            @endforeach
                            @endif
                            @else
                            <option value="">{{ __('messages.select') }}</option>
                            @if(!empty($content->custUserList))
                            @foreach($content->custUserList as $custuser)

                            @if(isset($custuser->irel__h_d_customer_master))
                            @if($custuser->rcu_customer_id ==   $custuser->irel__h_d_customer_master->cu_customer_ID)
                            <option value="{{  $custuser->irel__h_d_customer_master->cu_customer_ID }}">{{  $custuser->irel__h_d_customer_master->cu_customer_Shortname}} - {{  $custuser->irel__h_d_customer_master->cu_customer_Name }}</option>
                            @endif
                            @endif

                            @endforeach
                            @endif
                            @endif
                        </select>

my Controller

public function searchIncident(Request $request){

 if(isset($_GET["page"])) {
            $g_page = "?page=" . filter_var($_GET["page"], FILTER_SANITIZE_STRING);
        } else {
            $g_page = null;
        }

       // dd($g_page);

        $cust = filter_var($_GET["cu"], FILTER_SANITIZE_STRING);
        $customer = explode(' ',$cust);
        $branch = filter_var($_GET["br"], FILTER_SANITIZE_STRING);
        $category = filter_var($_GET["ct"], FILTER_SANITIZE_STRING);
        $pciisms = ['PCI','ISMS']  ;
        //dd($pciisms);
        $state = filter_var($_GET["stt"], FILTER_SANITIZE_STRING);
        $severity = filter_var($_GET["sv"], FILTER_SANITIZE_STRING);
        $logno = filter_var($_GET["cm"], FILTER_SANITIZE_STRING);
        $status = filter_var($_GET["st"], FILTER_SANITIZE_STRING);
        $group = filter_var($_GET["gr"], FILTER_SANITIZE_STRING);
        $createdby = filter_var($_GET["crtedBy"], FILTER_SANITIZE_STRING);
        $vendor = filter_var($_GET["ven"], FILTER_SANITIZE_STRING);
        $vendorrptno = filter_var($_GET["rptno"], FILTER_SANITIZE_STRING);
        $datefrom = filter_var($_GET["dtFrom"], FILTER_SANITIZE_STRING);
        $dateto = filter_var($_GET["dtTo"], FILTER_SANITIZE_STRING);
        $clsddatefrom = filter_var($_GET["dtClosedFrom"], FILTER_SANITIZE_STRING);
        $clsddateto = filter_var($_GET["dtClosedTo"], FILTER_SANITIZE_STRING);
        $probtype = filter_var($_GET["JpnProbType"], FILTER_SANITIZE_STRING);
        $caller = filter_var($_GET["callerName"], FILTER_SANITIZE_STRING);
        $person = filter_var($_GET["personName"], FILTER_SANITIZE_STRING);
        $custrptno = filter_var($_GET["cuRpt"], FILTER_SANITIZE_STRING);
        $assetsn = filter_var($_GET["assetSN"], FILTER_SANITIZE_STRING);
        $supplier = filter_var($_GET["sup"], FILTER_SANITIZE_STRING);
        $receivedby = filter_var($_GET["rcvdBy"], FILTER_SANITIZE_STRING);
        $closedby = filter_var($_GET["clsdBy"], FILTER_SANITIZE_STRING);

        $options = [
            'headers' => [
                'Content-Type' => 'application/json',
                'Accept' => 'application/json',
            ],
            'json' => [
                'customer' => $customer,
                'branch' => $branch,
                'category' => $category,
                'pciisms' => $pciisms,
                'state' => $state,
                'severity' => $severity,
                'logno' => $logno,
                'status' => $status,
                'group' => $group,
                'createdby' => $createdby,
                'vendor' => $vendor,
                'vendorrptno' => $vendorrptno,
                'datefrom' => $datefrom,
                'dateto' => $dateto,
                'clsddatefrom' => $clsddatefrom,
                'clsddateto' => $clsddateto,
                'probtype' => $probtype,
                'caller' => $caller,
                'person' => $person,
                'custrptno' => $custrptno,
                'assetsn' => $assetsn,
                'supplier' => $supplier,
                'receivedby' => $receivedby,
                'closedby' => $closedby,

            ],
        ];

        $response =  $this->client->post('searchIncident'.$g_page, $options)->getBody();
        $content = json_decode($response->getContents());
        $paginationRecord = $content->data->incidentList ;

        return view('incident.HDCaseMasterList', compact('paginationRecord'));

}

All data was set 15 per page . The data was pull from backend project. I expect all the data was shown on the next page. Hope its help and sorry for my english

Body:
Your undefined index is occurring here:

$cust = filter_var($_GET["cu"], FILTER_SANITIZE_STRING);

The quickest/easiest solution here (for the specific problem being asked about here, which is the problem of the undefined index error), would be to either (1) actually define it beforehand (not really best practise in this particular case, given we're talking about an index of $_GET; the reasons for my saying this being a little outside the scope of the question, so moving on..), or (2) just guard/check for the existence of it beforehand (the better of these two mentioned solutions).

Example of solution 1:

if (!isset($_GET["cu"])) {
    $_GET["cu"] = '';
}
$cust = filter_var($_GET["cu"], FILTER_SANITIZE_STRING);

Example of solution 2 (using fully-formed if/else; most verbose; may be more/less preferred, depending on code-style preferences):

if (isset($_GET["cu"])) {
    $cust = filter_var($_GET["cu"], FILTER_SANITIZE_STRING);
} else {
    $cust = "";
}

Example of solution 2 (using ternary; less verbose; may be more/less preferred, depending on code-style preferences):

$cust = filter_var(isset($_GET["cu"]) ? $_GET["cu"] : "", FILTER_SANITIZE_STRING);

Example of solution 2 (using null coalescence; least verbose; may be more/less preferred, depending on code-style preferences; best if targeting PHP versions >= 7 only; won't work if support for PHP < 7 is required for your project):

$cust = filter_var($_GET["cu"] ?? "", FILTER_SANITIZE_STRING);

Note: My reply is specifically addressing only the undefined index error. I haven't tested or audited your code, so whether there are other problems, or other things that need addressing, I wouldn't yet know.


问:
How to optimal K in K - Means Algorithm

Possible Duplicate:

  How do I determine k when using k-means clustering?

How can i choose the K initially, if i do not know about the data?

Can someone help me in choosing the K.

Thanks
Navin

答:
Seriously, what do you want to know? Do you want us to tell you some number? Or a strategy how to find the optimal k? You have to read a book or other resources about k-means, I'm pretty sure it is covered there.

There is something on Wikipedia about it:

http://en.wikipedia.org/wiki/Determining_the_number_of_clusters_in_a_data_set

Before you use an algorithm, read about it.

Title: How to optimal K in K - Means Algorithm