问:
Microsoft Booking Appointment Graph API -Only Post Request Not working
when I trying to create Microsoft Booking Appointment through Graph API
Only Post Request Not working .
GET , PATCH , DELETE Reuqest are working fine
through postman

same post request is working find on graph explorer platform . but not on posmant with
my auth token

my post API

```<code>https://graph.microsoft.com/v1.0/solutions/bookingBusinesses/XXXXXXXXXXXXXXX.com/appointments
</code>```

and body (took example from here)
excluded optional properties like servicename and customers

```<code>     {
    "@odata.type": "#microsoft.graph.bookingAppointment",
    "customerTimeZone": "America/Chicago",
    "smsNotificationsEnabled": false,
    "endDateTime": {
        "@odata.type": "#microsoft.graph.dateTimeTimeZone",
        "dateTime": "2023-01-02T14:30:00.0000000",
        "timeZone": "UTC"
    },
    "isLocationOnline": true,
    "optOutOfCustomerEmail": false,
    "anonymousJoinWebUrl": null,
    "postBuffer": "PT10M",
    "preBuffer": "PT5M",
    "price": 10,
    "priceType@odata.type": "#microsoft.graph.bookingPriceType",
    "priceType": "fixedPrice",
    "reminders@odata.type": "#Collection(microsoft.graph.bookingReminder)",
    "reminders": [
        {
            "@odata.type": "#microsoft.graph.bookingReminder",
            "message": "This service is tomorrow",
            "offset": "P1D",
            "recipients@odata.type": "#microsoft.graph.bookingReminderRecipients",
            "recipients": "allAttendees"
        },
        {
            "@odata.type": "#microsoft.graph.bookingReminder",
            "message": "Please be available to enjoy your lunch service.",
            "offset": "PT1H",
            "recipients@odata.type": "#microsoft.graph.bookingReminderRecipients",
            "recipients": "customer"
        },
        {
            "@odata.type": "#microsoft.graph.bookingReminder",
            "message": "Please check traffic for next cater.",
            "offset": "PT2H",
            "recipients@odata.type": "#microsoft.graph.bookingReminderRecipients",
            "recipients": "staff"
        }
    ],
    "serviceId": "XXXXXXXXXXXXXXXXXXXXX",
    "serviceLocation": {
        "@odata.type": "#microsoft.graph.location",
        "address": {
            "@odata.type": "#microsoft.graph.physicalAddress",
            "city": "Buffalo",
            "countryOrRegion": "USA",
            "postalCode": "98052",
            "postOfficeBox": null,
            "state": "NY",
            "street": "123 First Avenue",
            "type@odata.type": "#microsoft.graph.physicalAddressType",
            "type": null
        },
        "coordinates": null,
        "displayName": "Customer location",
        "locationEmailAddress": null,
        "locationType@odata.type": "#microsoft.graph.locationType",
        "locationType": null,
        "locationUri": null,
        "uniqueId": null,
        "uniqueIdType@odata.type": "#microsoft.graph.locationUniqueIdType",
        "uniqueIdType": null
    },
    "serviceNotes": "Customer requires punctual service.",
    "startDateTime": {
        "@odata.type": "#microsoft.graph.dateTimeTimeZone",
        "dateTime": "2023-01-02T14:00:00.0000000",
        "timeZone": "UTC"
    },
    "maximumAttendeesCount": 1,
    "filledAttendeesCount": 1
}
</code>```

Body:
when I trying to create Microsoft Booking Appointment through Graph API
Only Post Request Not working .
GET , PATCH , DELETE Reuqest are working fine
through postman

same post request is working find on graph explorer platform . but not on posmant with
my auth token

my post API

https://graph.microsoft.com/v1.0/solutions/bookingBusinesses/XXXXXXXXXXXXXXX.com/appointments

and body (took example from here)
excluded optional properties like servicename and customers

     {
    "@odata.type": "#microsoft.graph.bookingAppointment",
    "customerTimeZone": "America/Chicago",
    "smsNotificationsEnabled": false,
    "endDateTime": {
        "@odata.type": "#microsoft.graph.dateTimeTimeZone",
        "dateTime": "2023-01-02T14:30:00.0000000",
        "timeZone": "UTC"
    },
    "isLocationOnline": true,
    "optOutOfCustomerEmail": false,
    "anonymousJoinWebUrl": null,
    "postBuffer": "PT10M",
    "preBuffer": "PT5M",
    "price": 10,
    "priceType@odata.type": "#microsoft.graph.bookingPriceType",
    "priceType": "fixedPrice",
    "reminders@odata.type": "#Collection(microsoft.graph.bookingReminder)",
    "reminders": [
        {
            "@odata.type": "#microsoft.graph.bookingReminder",
            "message": "This service is tomorrow",
            "offset": "P1D",
            "recipients@odata.type": "#microsoft.graph.bookingReminderRecipients",
            "recipients": "allAttendees"
        },
        {
            "@odata.type": "#microsoft.graph.bookingReminder",
            "message": "Please be available to enjoy your lunch service.",
            "offset": "PT1H",
            "recipients@odata.type": "#microsoft.graph.bookingReminderRecipients",
            "recipients": "customer"
        },
        {
            "@odata.type": "#microsoft.graph.bookingReminder",
            "message": "Please check traffic for next cater.",
            "offset": "PT2H",
            "recipients@odata.type": "#microsoft.graph.bookingReminderRecipients",
            "recipients": "staff"
        }
    ],
    "serviceId": "XXXXXXXXXXXXXXXXXXXXX",
    "serviceLocation": {
        "@odata.type": "#microsoft.graph.location",
        "address": {
            "@odata.type": "#microsoft.graph.physicalAddress",
            "city": "Buffalo",
            "countryOrRegion": "USA",
            "postalCode": "98052",
            "postOfficeBox": null,
            "state": "NY",
            "street": "123 First Avenue",
            "type@odata.type": "#microsoft.graph.physicalAddressType",
            "type": null
        },
        "coordinates": null,
        "displayName": "Customer location",
        "locationEmailAddress": null,
        "locationType@odata.type": "#microsoft.graph.locationType",
        "locationType": null,
        "locationUri": null,
        "uniqueId": null,
        "uniqueIdType@odata.type": "#microsoft.graph.locationUniqueIdType",
        "uniqueIdType": null
    },
    "serviceNotes": "Customer requires punctual service.",
    "startDateTime": {
        "@odata.type": "#microsoft.graph.dateTimeTimeZone",
        "dateTime": "2023-01-02T14:00:00.0000000",
        "timeZone": "UTC"
    },
    "maximumAttendeesCount": 1,
    "filledAttendeesCount": 1
}


来源: stackexchange

问:
Why does the same asm code produce the different machine code
I'm reverse engineering a bootloader using IDA. When I use "patching" plugin to reassemble the file, the machine code it produced is different comparing to the code of the same instruction found in disassemble result.

What caused this phenomenon.

The segment info picture

The plugin GUI when I use

This is the code the plugin produced

00000008 | 01 D8       |   add     ax, bx

This is the code found in original file

0000000C | 03 C3       |   add     ax, bx

After discovering that, I substitute '03 C3' with '01 D8' and debug it. both of them works.

What's the difference?

Does the instruction set of intel is not the one-to-one relationship?

ContentLicense: CC BY-SA 4.0


问:
make csv file with coordinates of curve from png file - python
I have a png file with 2D coordinate system and a curve. How can a make a csv fill with some point that i will choose by clicking with the mouse (i mean i will click with my mouse on the png and that why i will chose where the coordinate system is ans some point on the curve that will be save to csv file with their x,y coordinates in relation to the coordinate system i chose)

to tell the true i have no direction, i want to be able to plot the curve i have in the png from csv file wite the same coordinate system


问:
Javascript: How can I access the ImageData data properties when generated as a function?
Consider the following case where I have a base64 image that I want to turn into an array and access its properties.

While the code works, I am unable to access its properties like so:

```<code>console.log('imageData', imageData)
</code>```

What can I do to get at the underlying data?

A MWE:

```<code>    var str = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAApgAAAKYB3X3/OAAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAANCSURBVEiJtZZPbBtFFMZ/M7ubXdtdb1xSFyeilBapySVU8h8OoFaooFSqiihIVIpQBKci6KEg9Q6H9kovIHoCIVQJJCKE1ENFjnAgcaSGC6rEnxBwA04Tx43t2FnvDAfjkNibxgHxnWb2e/u992bee7tCa00YFsffekFY+nUzFtjW0LrvjRXrCDIAaPLlW0nHL0SsZtVoaF98mLrx3pdhOqLtYPHChahZcYYO7KvPFxvRl5XPp1sN3adWiD1ZAqD6XYK1b/dvE5IWryTt2udLFedwc1+9kLp+vbbpoDh+6TklxBeAi9TL0taeWpdmZzQDry0AcO+jQ12RyohqqoYoo8RDwJrU+qXkjWtfi8Xxt58BdQuwQs9qC/afLwCw8tnQbqYAPsgxE1S6F3EAIXux2oQFKm0ihMsOF71dHYx+f3NND68ghCu1YIoePPQN1pGRABkJ6Bus96CutRZMydTl+TvuiRW1m3n0eDl0vRPcEysqdXn+jsQPsrHMquGeXEaY4Yk4wxWcY5V/9scqOMOVUFthatyTy8QyqwZ+kDURKoMWxNKr2EeqVKcTNOajqKoBgOE28U4tdQl5p5bwCw7BWquaZSzAPlwjlithJtp3pTImSqQRrb2Z8PHGigD4RZuNX6JYj6wj7O4TFLbCO/Mn/m8R+h6rYSUb3ekokRY6f/YukArN979jcW+V/S8g0eT/N3VN3kTqWbQ428m9/8k0P/1aIhF36PccEl6EhOcAUCrXKZXXWS3XKd2vc/TRBG9O5ELC17MmWubD2nKhUKZa26Ba2+D3P+4/MNCFwg59oWVeYhkzgN/JDR8deKBoD7Y+ljEjGZ0sosXVTvbc6RHirr2reNy1OXd6pJsQ+gqjk8VWFYmHrwBzW/n+uMPFiRwHB2I7ih8ciHFxIkd/3Omk5tCDV1t+2nNu5sxxpDFNx+huNhVT3/zMDz8usXC3ddaHBj1GHj/As08fwTS7Kt1HBTmyN29vdwAw+/wbwLVOJ3uAD1wi/dUH7Qei66PfyuRj4Ik9is+hglfbkbfR3cnZm7chlUWLdwmprtCohX4HUtlOcQjLYCu+fzGJH2QRKvP3UNz8bWk1qMxjGTOMThZ3kvgLI5AzFfo379UAAAAASUVORK5CYII="
    var canvas = document.createElement("canvas");
    var ctx = canvas.getContext('2d');

    var image = new Image()
    image.onload = function() {
      ctx.drawImage(image, 0, 0);
      var imageData = ctx.getImageData(0, 0, image.width, image.height);
      // only works here, but cant use later
      console.log(imageData)
    }
    image.src = str;
    console.log('imageData', imageData)
</code>```

If I run the code as follows; it will not run 100% of the time:

```<code>    var image = new Image()
    image.src = await str;
    ctx.drawImage(image, 0, 0)
    var imageData = ctx.getImageData(0, 0, image.width, image.height);
    console.log('imageData', imageData)
</code>```

Yielding:

Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The source width is 0.

Body:
Consider the following case where I have a base64 image that I want to turn into an array and access its properties.

While the code works, I am unable to access its properties like so:

console.log('imageData', imageData)

What can I do to get at the underlying data?

A MWE:

    var str = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAApgAAAKYB3X3/OAAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAANCSURBVEiJtZZPbBtFFMZ/M7ubXdtdb1xSFyeilBapySVU8h8OoFaooFSqiihIVIpQBKci6KEg9Q6H9kovIHoCIVQJJCKE1ENFjnAgcaSGC6rEnxBwA04Tx43t2FnvDAfjkNibxgHxnWb2e/u992bee7tCa00YFsffekFY+nUzFtjW0LrvjRXrCDIAaPLlW0nHL0SsZtVoaF98mLrx3pdhOqLtYPHChahZcYYO7KvPFxvRl5XPp1sN3adWiD1ZAqD6XYK1b/dvE5IWryTt2udLFedwc1+9kLp+vbbpoDh+6TklxBeAi9TL0taeWpdmZzQDry0AcO+jQ12RyohqqoYoo8RDwJrU+qXkjWtfi8Xxt58BdQuwQs9qC/afLwCw8tnQbqYAPsgxE1S6F3EAIXux2oQFKm0ihMsOF71dHYx+f3NND68ghCu1YIoePPQN1pGRABkJ6Bus96CutRZMydTl+TvuiRW1m3n0eDl0vRPcEysqdXn+jsQPsrHMquGeXEaY4Yk4wxWcY5V/9scqOMOVUFthatyTy8QyqwZ+kDURKoMWxNKr2EeqVKcTNOajqKoBgOE28U4tdQl5p5bwCw7BWquaZSzAPlwjlithJtp3pTImSqQRrb2Z8PHGigD4RZuNX6JYj6wj7O4TFLbCO/Mn/m8R+h6rYSUb3ekokRY6f/YukArN979jcW+V/S8g0eT/N3VN3kTqWbQ428m9/8k0P/1aIhF36PccEl6EhOcAUCrXKZXXWS3XKd2vc/TRBG9O5ELC17MmWubD2nKhUKZa26Ba2+D3P+4/MNCFwg59oWVeYhkzgN/JDR8deKBoD7Y+ljEjGZ0sosXVTvbc6RHirr2reNy1OXd6pJsQ+gqjk8VWFYmHrwBzW/n+uMPFiRwHB2I7ih8ciHFxIkd/3Omk5tCDV1t+2nNu5sxxpDFNx+huNhVT3/zMDz8usXC3ddaHBj1GHj/As08fwTS7Kt1HBTmyN29vdwAw+/wbwLVOJ3uAD1wi/dUH7Qei66PfyuRj4Ik9is+hglfbkbfR3cnZm7chlUWLdwmprtCohX4HUtlOcQjLYCu+fzGJH2QRKvP3UNz8bWk1qMxjGTOMThZ3kvgLI5AzFfo379UAAAAASUVORK5CYII="
    var canvas = document.createElement("canvas");
    var ctx = canvas.getContext('2d');

    var image = new Image()
    image.onload = function() {
      ctx.drawImage(image, 0, 0);
      var imageData = ctx.getImageData(0, 0, image.width, image.height);
      // only works here, but cant use later
      console.log(imageData)
    }
    image.src = str;
    console.log('imageData', imageData)

If I run the code as follows; it will not run 100% of the time:

    var image = new Image()
    image.src = await str;
    ctx.drawImage(image, 0, 0)
    var imageData = ctx.getImageData(0, 0, image.width, image.height);
    console.log('imageData', imageData)

Yielding:

Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The source width is 0.


问:
Fill data in one data frame using values from other data frame : Python
I have two data frames and I need to append data from df2 to df1 using 'ID' column. df1 has duplicates on same ID whereas df2 has ID as primary key. I need to add data from df2 to df1 such that :

df1 :

```<code>|Index|   ID|Last Updated|
|    0|   A1|   1.10.2022|
|    1|   A2|   12.11.2022|
|    2|   A3|   3.12.2022|
|    3|   C1|   4.12.2022|
|    4|   C1|   19.12.2022|
</code>```

df2 :

```<code>|Index|   ID|    Title |
|    0|   A1|   system1|
|    1|   A2|   system2|
|    2|   A3|   system3|
|    3|   C1|   system4|
</code>```

expected output (df3):

```<code>|Index|   ID|Last Updated|    Title |
|    0|   A1|   1.10.2022|   system1|
|    1|   A2|   12.11.2022|   system2|
|    2|   A3|   3.12.2022|   system3|
|    3|   C1|   4.12.2022|   system4|
|    4|   C1|   19.12.2022|   system4|
</code>```

I tried a brute approach to solve this:

```<code>for idx, data in df1.iterrows():
    temp = df2[df2['id'] == data['id']]
    column_list = temp.columns.to_list()
    for column in column_list:
        df1.at[idx, column] = temp.iloc[0][column]
</code>```

I want to understand if there is any direct/better approach to do this?

Body:
I have two data frames and I need to append data from df2 to df1 using 'ID' column. df1 has duplicates on same ID whereas df2 has ID as primary key. I need to add data from df2 to df1 such that :

df1 :

|Index|   ID|Last Updated|
|    0|   A1|   1.10.2022|
|    1|   A2|   12.11.2022|
|    2|   A3|   3.12.2022|
|    3|   C1|   4.12.2022|
|    4|   C1|   19.12.2022|

df2 :

|Index|   ID|    Title |
|    0|   A1|   system1|
|    1|   A2|   system2|
|    2|   A3|   system3|
|    3|   C1|   system4|

expected output (df3):

|Index|   ID|Last Updated|    Title |
|    0|   A1|   1.10.2022|   system1|
|    1|   A2|   12.11.2022|   system2|
|    2|   A3|   3.12.2022|   system3|
|    3|   C1|   4.12.2022|   system4|
|    4|   C1|   19.12.2022|   system4|

I tried a brute approach to solve this:

for idx, data in df1.iterrows():
    temp = df2[df2['id'] == data['id']]
    column_list = temp.columns.to_list()
    for column in column_list:
        df1.at[idx, column] = temp.iloc[0][column]

I want to understand if there is any direct/better approach to do this?


问:
Kendo timeline view multiple departments but not same attendees
We are working with Kendo UI for Angular and having scheduler timeline view as one of the component.

We have two sections on the Y-axis: department & attendees. Under Mechanics three names are there: Alex, Bob, Charlie.
Similarly, we want to have multiple departments but not same attendees will be there in all departments.
We want different or same attendees under different departments based on the business need.

is it possible to have this with angular & how?


问:
My app has ACCESS_BACKGROUND_LOCATION but I still get Foreground service started from background can not have location
Starting Android 11 you need to explain to the user why you need ACCESS_BACKGROUND_LOCATION and redirect the user to the app’s settings screen.

I ask the user and the user allows for the location to be used all the time.

```<code>activity.requestPermissions(
                    arrayOf(Manifest.permission.ACCESS_BACKGROUND_LOCATION),
                    backgroundLocationRequestCode
                )
</code>```

Then a reboot happens and I have a BootCompleteReceiver : BroadcastReceiver that starts my Foreground Service from the background with an ongoing notification.
I am tracking location/GPS in the background and I expect it to be working as intended, but I get this error in the logcat after BOOT_COMPLETED:

```<code>W/ActivityManager: Foreground service started from background can not have location/camera/microphone access: service com.example.myapp/.core.service.MyForegroundService
</code>```

What am I missing here and how can I solve the issue?

Body:
Starting Android 11 you need to explain to the user why you need ACCESS_BACKGROUND_LOCATION and redirect the user to the app’s settings screen.

I ask the user and the user allows for the location to be used all the time.

activity.requestPermissions(
                    arrayOf(Manifest.permission.ACCESS_BACKGROUND_LOCATION),
                    backgroundLocationRequestCode
                )

Then a reboot happens and I have a BootCompleteReceiver : BroadcastReceiver that starts my Foreground Service from the background with an ongoing notification.
I am tracking location/GPS in the background and I expect it to be working as intended, but I get this error in the logcat after BOOT_COMPLETED:

W/ActivityManager: Foreground service started from background can not have location/camera/microphone access: service com.example.myapp/.core.service.MyForegroundService

What am I missing here and how can I solve the issue?


问:
Plotting confidence intervals for linear regression
I am trying to plot confidence intervals in my matplotlib plot with the seaborn style (similar to what the regplot fuction in seaborn would give but with the ability to run statistics from the regression).

My current plot looks like this:

Which is created with the following code:

```<code>#Read in proper dataframe
storms_per_year = pd.read_csv('number_of_storms_per_year.csv')

#Create linear regression function

def lin_reg(x,y):
    linreg = LinearRegression().fit(x,y)
    print(linreg.intercept_, linreg.coef_, linreg.score(x,y))
    n = sm.add_constant(x)
    results = sm.OLS(y, n).fit()
    conf_interval = results.conf_int(0.05)
    print(results.summary())
pass

#Define variables for linear regression - frequency
x_col ='season'
y_col = 'days'
x = storms_per_year[x_col]
y = storms_per_year[y_col]
x_array = np.array(x).reshape(-1,1)
y_array = np.array(y).reshape(-1,1)

linreg = LinearRegression().fit(x_array,y_array)

#Perform linear regression for frequency
lin_reg(x_array,y_array)

#Plot
sns.set_theme(context='notebook', style='darkgrid')
sns.light_palette("#79C")

plt.scatter(x_array,y_array, alpha = 0.25)
plt.plot(x_array,linreg.predict(x_array), label='y=-0.0291x+69.2610')
plt.xlabel('Season')
plt.ylabel('Number of Storms')
plt.title('Frequency of Storms Over Time')
plt.legend()
plt.show
</code>```

I have tried the following with successful confidence intervals:

```<code>import pydove as dv
#Plot-----------------------------
#Set variables
x_col ='season'
y_col = 'days'
x = storms_per_year[x_col]
y = storms_per_year[y_col]

fig, ax = plt.subplots()
res = dv.regplot(x,y, ax=ax )
ax.set_xlabel('Season')
ax.set_ylabel('Number of Storms')
ax.set_title('Frequency of Storms Over Time')
fig.set_label(res)

reg_line = mlines.Line2D([],[])

plt.legend()
res.summary()
</code>```

Which results in:

But then I cannot add the statistical info to the legend as I want to do. Any suggestions are welcome.

Body:
I am trying to plot confidence intervals in my matplotlib plot with the seaborn style (similar to what the regplot fuction in seaborn would give but with the ability to run statistics from the regression).

My current plot looks like this:

Which is created with the following code:

#Read in proper dataframe
storms_per_year = pd.read_csv('number_of_storms_per_year.csv')

#Create linear regression function

def lin_reg(x,y):
    linreg = LinearRegression().fit(x,y)
    print(linreg.intercept_, linreg.coef_, linreg.score(x,y))
    n = sm.add_constant(x)
    results = sm.OLS(y, n).fit()
    conf_interval = results.conf_int(0.05)
    print(results.summary())
pass

#Define variables for linear regression - frequency
x_col ='season'
y_col = 'days'
x = storms_per_year[x_col]
y = storms_per_year[y_col]
x_array = np.array(x).reshape(-1,1)
y_array = np.array(y).reshape(-1,1)

linreg = LinearRegression().fit(x_array,y_array)

#Perform linear regression for frequency
lin_reg(x_array,y_array)

#Plot
sns.set_theme(context='notebook', style='darkgrid')
sns.light_palette("#79C")

plt.scatter(x_array,y_array, alpha = 0.25)
plt.plot(x_array,linreg.predict(x_array), label='y=-0.0291x+69.2610')
plt.xlabel('Season')
plt.ylabel('Number of Storms')
plt.title('Frequency of Storms Over Time')
plt.legend()
plt.show

I have tried the following with successful confidence intervals:

import pydove as dv
#Plot-----------------------------
#Set variables
x_col ='season'
y_col = 'days'
x = storms_per_year[x_col]
y = storms_per_year[y_col]

fig, ax = plt.subplots()
res = dv.regplot(x,y, ax=ax )
ax.set_xlabel('Season')
ax.set_ylabel('Number of Storms')
ax.set_title('Frequency of Storms Over Time')
fig.set_label(res)

reg_line = mlines.Line2D([],[])

plt.legend()
res.summary()

Which results in:

But then I cannot add the statistical info to the legend as I want to do. Any suggestions are welcome.


问:
How to close udp socket correctly, python
I have a small issue.

How can I close UDP-socket on the server-side correctly? Below you can find a part of my code. I guess, you do not need the whole code for my case.

Server Code

```<code>import ns_beam  # my module
import socket
import pickle

host = socket.gethostname()
port_client = 60000
port_server = 50000
CLIENT_ADDRESS = (host, port_client)

server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind((host, port_server))

while True:
    message, address = server_socket.recvfrom(1024)
    recv_data = pickle.loads(message)  # convert data to pickle
    print(f"Received force from PS = {round(recv_data, 3)} [kN]")

    result = ns_beam.num_sub_structure(f_sensor=recv_data, num_elem_tot=element_number)  #  calculation
    print(f"Displacement of NS = {round(result, 3)} [mm]")

    # code to send data
    sent_data = pickle.dumps(result)       # convert data to pickle
    server_socket.sendto(sent_data,        # data to be sent
                         CLIENT_ADDRESS)   # details of destination

server_socket.close()
</code>```

Client Code

```<code>import ps_truss # my module
import socket
import pickle
import time

host = socket.gethostname()
port_client = 60000
port_server = 50000
SERVER_ADDRESS = (host, port_server)

client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client_socket.bind((host, port_client))

# ===============================
# ===============================
# create an array for E_i, where every next E_i is 10% less than previous
E_arr = []
E = 210000  # [N/mm2]
E_0 = 210000  # [N/mm2]
while E > E_0 * 0.3:
    E = E - E * 0.1
    E_arr.append(E)
# ===============================
# ===============================

# ============ initial step. Start
result_init = ps_truss.ps_sub_structure(v_2=v_2_init, e_mod=E)  # calculation
# code to cent data
data_send_init = pickle.dumps(result_init)  # convert data to pickle
client_socket.sendto(data_send_init,  # data to be sent
                     SERVER_ADDRESS)  # details of destination
# ============ initial step. End

counter = 0

while True:

    for E_i in E_arr:
        message, address = client_socket.recvfrom(1024)
        recv_data = pickle.loads(message)
        print(f'received displacement from NS:{round(recv_data, 3)} [mm]')

        time.sleep(1)
        result = ps_truss.ps_sub_structure(v_2=recv_data, e_mod=E_i)  # calculation
        print(f'force from PS:{round(result, 3)} [kN]')

        # code to cent data
        sent_data = pickle.dumps(result)  # convert data to pickle
        client_socket.sendto(sent_data,  # data to be sent
                             SERVER_ADDRESS)  # details of destination

        counter += 1
        print(counter)
        if counter > len(E_arr):
            break
break

print("The client socket is closed")
client_socket.close()
</code>```

On the Server Side the code server_socket.close() is unreachable. I understand, that first of all the while loop shall be closed.

My idea is as long I receive the data from client, the while loop will not be interrupted. If I do not receive data (e.g. for 30 sec.) the server shall close a socket.

Could you please help me to implement this?

Many thanks in advance!

Body:
I have a small issue.

How can I close UDP-socket on the server-side correctly? Below you can find a part of my code. I guess, you do not need the whole code for my case.

Server Code

import ns_beam  # my module
import socket
import pickle

host = socket.gethostname()
port_client = 60000
port_server = 50000
CLIENT_ADDRESS = (host, port_client)

server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind((host, port_server))

while True:
    message, address = server_socket.recvfrom(1024)
    recv_data = pickle.loads(message)  # convert data to pickle
    print(f"Received force from PS = {round(recv_data, 3)} [kN]")

    result = ns_beam.num_sub_structure(f_sensor=recv_data, num_elem_tot=element_number)  #  calculation
    print(f"Displacement of NS = {round(result, 3)} [mm]")

    # code to send data
    sent_data = pickle.dumps(result)       # convert data to pickle
    server_socket.sendto(sent_data,        # data to be sent
                         CLIENT_ADDRESS)   # details of destination

server_socket.close()

Client Code

import ps_truss # my module
import socket
import pickle
import time

host = socket.gethostname()
port_client = 60000
port_server = 50000
SERVER_ADDRESS = (host, port_server)

client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client_socket.bind((host, port_client))

# ===============================
# ===============================
# create an array for E_i, where every next E_i is 10% less than previous
E_arr = []
E = 210000  # [N/mm2]
E_0 = 210000  # [N/mm2]
while E > E_0 * 0.3:
    E = E - E * 0.1
    E_arr.append(E)
# ===============================
# ===============================

# ============ initial step. Start
result_init = ps_truss.ps_sub_structure(v_2=v_2_init, e_mod=E)  # calculation
# code to cent data
data_send_init = pickle.dumps(result_init)  # convert data to pickle
client_socket.sendto(data_send_init,  # data to be sent
                     SERVER_ADDRESS)  # details of destination
# ============ initial step. End

counter = 0

while True:

    for E_i in E_arr:
        message, address = client_socket.recvfrom(1024)
        recv_data = pickle.loads(message)
        print(f'received displacement from NS:{round(recv_data, 3)} [mm]')

        time.sleep(1)
        result = ps_truss.ps_sub_structure(v_2=recv_data, e_mod=E_i)  # calculation
        print(f'force from PS:{round(result, 3)} [kN]')

        # code to cent data
        sent_data = pickle.dumps(result)  # convert data to pickle
        client_socket.sendto(sent_data,  # data to be sent
                             SERVER_ADDRESS)  # details of destination

        counter += 1
        print(counter)
        if counter > len(E_arr):
            break
break

print("The client socket is closed")
client_socket.close()

On the Server Side the code server_socket.close() is unreachable. I understand, that first of all the while loop shall be closed.

My idea is as long I receive the data from client, the while loop will not be interrupted. If I do not receive data (e.g. for 30 sec.) the server shall close a socket.

Could you please help me to implement this?

Many thanks in advance!


问:
Emulating dashed lines with LineCollection
Consider data in a dictionary which may stem from a stochastic method or a deterministic method. If it is stochastic, then there will be a different offset for each run after which a metric was tracked, while a deterministic method will have only a single entry of values with a fixed offset of 2.

To be precise, such (emulated) data is at hand:

values_dict = {
    "stochastic (A)": [
        rng.normal(100, variance, size=n_iters - offset)
        / np.arange(offset, n_iters)
        for variance, offset in zip(
            rng.integers(0.5, 5, size=20), (rng.integers(5, 300, size=20))
        )
    ],
    "stochastic (S)": [
        rng.normal(100, variance, size=n_iters - offset)
        / (np.arange(offset, n_iters) ** 1.5)
        for variance, offset in zip(
            rng.integers(0.5, 5, size=20), (rng.integers(5, 300, size=20))
        )
    ],
    "deterministic (A)": [
        rng.normal(100, 1, size=n_iters - 2) / (np.arange(2, n_iters) ** 2)
    ],
    "deterministic (S)": [
        rng.normal(100, 1, size=n_iters - 2) / (np.arange(2, n_iters) ** 2.5)
    ],
}

```
<p>I plot a line for each method and the line is dashed depending on whether it has a <code>(A)</code> in its name. The stochastic methods are plotted via a <code>LineCollection</code>, in order to vary the <code>linewidth</code> and <code>alpha</code> over the number of iterations (this should highlight some statistical unreliability of the early data). The current result looks like this:</p>
<p><img src="https://i.stack.imgur.com/ygFBF.png" alt="enter image description here" /></p>
<p>Now, the problem is that <code>stochastic (A)</code> is not dashed, since adding <code>linestyle="--"</code> means nothing for such short lines in quick succession.
So, here comes my question:</p>
<p>Is there a way to emulate dashed lines in my linecollection that matches the style of the other rendered dashed line?</p>
<p>My entire code to produce this MWP is the following:</p>
<pre class="lang-py prettyprint-override"><code>from typing import Dict, List

import matplotlib.cm
import numpy as np
import torch
from matplotlib import pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.lines import Line2D
from collections import Counter

def prep_data(iters_run: int, value_list: List[List[float]]):
    x = np.arange(1, iters_run + 1)

    iteration_counts = np.flip(
        np.sort(np.asarray([len(vals) for vals in value_list])), 0
    )
    iter_beginnings = iters_run - iteration_counts
    freq_arr = np.asarray(
        sorted(Counter(iter_beginnings).items(), key=lambda x: x[0]),
        dtype=float,
    )
    absolute_freq = np.cumsum(freq_arr, axis=0)[:, 1]
    relative_freq = absolute_freq / len(value_list)
    iter_buckets = freq_arr[:, 0].astype(int)
    iter_to_bucket = (
        np.searchsorted(
            iter_buckets,
            x - 1,  # x is the 'logical' x scale to plot (iteration 1...T),
            # but values are index starting from 0, so -1 to get the index scale
            side="right",
        )
        - 1
    )
    no_value_mask = iter_to_bucket == -1
    no_value_iters = x[no_value_mask]
    absolute_freq_per_iter = np.concatenate(
        [
            np.zeros(no_value_iters.size),
            absolute_freq[iter_to_bucket[~no_value_mask]],
        ]
    )
    relative_freq_per_iter = np.concatenate(
        [
            np.zeros(no_value_iters.size),
            relative_freq[iter_to_bucket[~no_value_mask]],
        ]
    )
    padded_iter_values_matrix = (
        torch.nn.utils.rnn.pad_sequence(
            [  # full-length zeros tensor to force padding for the entire run_iters length
                torch.zeros(iters_run)
            ]
            + [torch.Tensor(list(reversed(a))) for a in value_list],
            batch_first=True,
        )
        .flip(dims=(1,))
        .numpy()
    )
    nanpadded_iter_values_matrix = np.where(
        padded_iter_values_matrix == 0, np.nan, padded_iter_values_matrix
    )
    sum_band = padded_iter_values_matrix.sum(axis=0)
    mean_band = sum_band / absolute_freq_per_iter
    stderr = np.nanstd(nanpadded_iter_values_matrix, ddof=1, axis=0) / np.sqrt(
        np.isnan(nanpadded_iter_values_matrix).sum(axis=0)
    )
    nan_mask = np.isnan(mean_band)
    x_to_plot = (x - 1)[~nan_mask]
    # repackage the x, y data points as a list of 2D coordinates
    mean_to_plot = mean_band[~nan_mask]
    stderr_to_plot = stderr[~nan_mask]
    return (
        x_to_plot,
        mean_to_plot,
        stderr_to_plot,
        relative_freq[iter_to_bucket[~no_value_mask]],
        relative_freq_per_iter,
    )

def plot(
    iters_run: int,
    method_to_data_dict: Dict[str, List[List[float]]],
    save_name: str,
    linewidth=1,
):
    with plt.style.context("bmh"):
        fig, ax = plt.subplots()
        cmap = matplotlib.cm.get_cmap("tab20")

        manual_legend_handles = []

        for i, (method, list_of_values) in enumerate(method_to_data_dict.items()):

            linestyle = "--" if "(A)" in method else "-"

            color = cmap(i)

            if len(list_of_values) == 1:
                iter_offset = iters_run - len(list_of_values[0])
                ax.plot(
                    np.arange(iter_offset, iters_run)
                    + 1,  # +1 to plot from iteration 1 on the scale, not 0
                    list_of_values[0],
                    label=method,
                    linewidth=linewidth,
                    linestyle=linestyle,
                    color=color,
                )
            else:
                (
                    x_to_plot,
                    mean_to_plot,
                    stderr_to_plot,
                    relative_freq_existing_values,
                    relative_freq_for_all_iter,
                ) = prep_data(iters_run, list_of_values)

                points = np.array([x_to_plot, mean_to_plot]).T.reshape(-1, 1, 2)
                segments = np.concatenate([points[:-1], points[1:]], axis=1)

                lc = LineCollection(
                    segments,
                    linewidths=relative_freq_for_all_iter * linewidth,
                    color=color,
                    alpha=relative_freq_for_all_iter,
                )
                ax.add_collection(lc)
                # add the legend entry manually
                manual_legend_handles.append(
                    Line2D(
                        [0],
                        [0],
                        label=method,
                        linewidth=linewidth,
                        linestyle=linestyle,
                        color=color,
                    )
                )

        ax.set_xlabel("Iteration")
        ax.set_ylabel("Log scale metric")
        ax.set_yscale("log", base=10)
        ax.set_title(f"My Title")
        manual_legend_handles.extend(ax.get_legend_handles_labels()[0])
        ax.legend(
            handles=manual_legend_handles,
            loc="upper center",
            bbox_to_anchor=(0.5, -0.1),
            fancybox=True,
            shadow=True,
            ncol=4,
        )
        plt.savefig(f"{save_name}_iters_{iters_run}.png", dpi=200, bbox_inches="tight")

if __name__ == "__main__":
    n_iters = 1000

    rng = np.random.default_rng(0)
    values_dict = {
        "stochastic (A)": [
            rng.normal(100, variance, size=n_iters - offset)
            / np.arange(offset, n_iters)
            for variance, offset in zip(
                rng.integers(0.5, 5, size=20), (rng.integers(5, 300, size=20))
            )
        ],
        "stochastic (S)": [
            rng.normal(100, variance, size=n_iters - offset)
            / (np.arange(offset, n_iters) ** 1.5)
            for variance, offset in zip(
                rng.integers(0.5, 5, size=20), (rng.integers(5, 300, size=20))
            )
        ],
        "deterministic (A)": [
            rng.normal(100, 1, size=n_iters - 2) / (np.arange(2, n_iters) ** 2)
        ],
        "deterministic (S)": [
            rng.normal(100, 1, size=n_iters - 2) / (np.arange(2, n_iters) ** 2.5)
        ],
    }

    plot(
        n_iters,
        values_dict,
        save_name=f"minimal_working_example",
    )

</code>```

Body:
Consider data in a dictionary which may stem from a stochastic method or a deterministic method. If it is stochastic, then there will be a different offset for each run after which a metric was tracked, while a deterministic method will have only a single entry of values with a fixed offset of 2.

To be precise, such (emulated) data is at hand:

values_dict = {
    "stochastic (A)": [
        rng.normal(100, variance, size=n_iters - offset)
        / np.arange(offset, n_iters)
        for variance, offset in zip(
            rng.integers(0.5, 5, size=20), (rng.integers(5, 300, size=20))
        )
    ],
    "stochastic (S)": [
        rng.normal(100, variance, size=n_iters - offset)
        / (np.arange(offset, n_iters) ** 1.5)
        for variance, offset in zip(
            rng.integers(0.5, 5, size=20), (rng.integers(5, 300, size=20))
        )
    ],
    "deterministic (A)": [
        rng.normal(100, 1, size=n_iters - 2) / (np.arange(2, n_iters) ** 2)
    ],
    "deterministic (S)": [
        rng.normal(100, 1, size=n_iters - 2) / (np.arange(2, n_iters) ** 2.5)
    ],
}

I plot a line for each method and the line is dashed depending on whether it has a (A) in its name. The stochastic methods are plotted via a LineCollection, in order to vary the linewidth and alpha over the number of iterations (this should highlight some statistical unreliability of the early data). The current result looks like this:

Now, the problem is that stochastic (A) is not dashed, since adding linestyle="--" means nothing for such short lines in quick succession.
So, here comes my question:

Is there a way to emulate dashed lines in my linecollection that matches the style of the other rendered dashed line?

My entire code to produce this MWP is the following:

from typing import Dict, List

import matplotlib.cm
import numpy as np
import torch
from matplotlib import pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.lines import Line2D
from collections import Counter

def prep_data(iters_run: int, value_list: List[List[float]]):
    x = np.arange(1, iters_run + 1)

    iteration_counts = np.flip(
        np.sort(np.asarray([len(vals) for vals in value_list])), 0
    )
    iter_beginnings = iters_run - iteration_counts
    freq_arr = np.asarray(
        sorted(Counter(iter_beginnings).items(), key=lambda x: x[0]),
        dtype=float,
    )
    absolute_freq = np.cumsum(freq_arr, axis=0)[:, 1]
    relative_freq = absolute_freq / len(value_list)
    iter_buckets = freq_arr[:, 0].astype(int)
    iter_to_bucket = (
        np.searchsorted(
            iter_buckets,
            x - 1,  # x is the 'logical' x scale to plot (iteration 1...T),
            # but values are index starting from 0, so -1 to get the index scale
            side="right",
        )
        - 1
    )
    no_value_mask = iter_to_bucket == -1
    no_value_iters = x[no_value_mask]
    absolute_freq_per_iter = np.concatenate(
        [
            np.zeros(no_value_iters.size),
            absolute_freq[iter_to_bucket[~no_value_mask]],
        ]
    )
    relative_freq_per_iter = np.concatenate(
        [
            np.zeros(no_value_iters.size),
            relative_freq[iter_to_bucket[~no_value_mask]],
        ]
    )
    padded_iter_values_matrix = (
        torch.nn.utils.rnn.pad_sequence(
            [  # full-length zeros tensor to force padding for the entire run_iters length
                torch.zeros(iters_run)
            ]
            + [torch.Tensor(list(reversed(a))) for a in value_list],
            batch_first=True,
        )
        .flip(dims=(1,))
        .numpy()
    )
    nanpadded_iter_values_matrix = np.where(
        padded_iter_values_matrix == 0, np.nan, padded_iter_values_matrix
    )
    sum_band = padded_iter_values_matrix.sum(axis=0)
    mean_band = sum_band / absolute_freq_per_iter
    stderr = np.nanstd(nanpadded_iter_values_matrix, ddof=1, axis=0) / np.sqrt(
        np.isnan(nanpadded_iter_values_matrix).sum(axis=0)
    )
    nan_mask = np.isnan(mean_band)
    x_to_plot = (x - 1)[~nan_mask]
    # repackage the x, y data points as a list of 2D coordinates
    mean_to_plot = mean_band[~nan_mask]
    stderr_to_plot = stderr[~nan_mask]
    return (
        x_to_plot,
        mean_to_plot,
        stderr_to_plot,
        relative_freq[iter_to_bucket[~no_value_mask]],
        relative_freq_per_iter,
    )

def plot(
    iters_run: int,
    method_to_data_dict: Dict[str, List[List[float]]],
    save_name: str,
    linewidth=1,
):
    with plt.style.context("bmh"):
        fig, ax = plt.subplots()
        cmap = matplotlib.cm.get_cmap("tab20")

        manual_legend_handles = []

        for i, (method, list_of_values) in enumerate(method_to_data_dict.items()):

            linestyle = "--" if "(A)" in method else "-"

            color = cmap(i)

            if len(list_of_values) == 1:
                iter_offset = iters_run - len(list_of_values[0])
                ax.plot(
                    np.arange(iter_offset, iters_run)
                    + 1,  # +1 to plot from iteration 1 on the scale, not 0
                    list_of_values[0],
                    label=method,
                    linewidth=linewidth,
                    linestyle=linestyle,
                    color=color,
                )
            else:
                (
                    x_to_plot,
                    mean_to_plot,
                    stderr_to_plot,
                    relative_freq_existing_values,
                    relative_freq_for_all_iter,
                ) = prep_data(iters_run, list_of_values)

                points = np.array([x_to_plot, mean_to_plot]).T.reshape(-1, 1, 2)
                segments = np.concatenate([points[:-1], points[1:]], axis=1)

                lc = LineCollection(
                    segments,
                    linewidths=relative_freq_for_all_iter * linewidth,
                    color=color,
                    alpha=relative_freq_for_all_iter,
                )
                ax.add_collection(lc)
                # add the legend entry manually
                manual_legend_handles.append(
                    Line2D(
                        [0],
                        [0],
                        label=method,
                        linewidth=linewidth,
                        linestyle=linestyle,
                        color=color,
                    )
                )

        ax.set_xlabel("Iteration")
        ax.set_ylabel("Log scale metric")
        ax.set_yscale("log", base=10)
        ax.set_title(f"My Title")
        manual_legend_handles.extend(ax.get_legend_handles_labels()[0])
        ax.legend(
            handles=manual_legend_handles,
            loc="upper center",
            bbox_to_anchor=(0.5, -0.1),
            fancybox=True,
            shadow=True,
            ncol=4,
        )
        plt.savefig(f"{save_name}_iters_{iters_run}.png", dpi=200, bbox_inches="tight")

if __name__ == "__main__":
    n_iters = 1000

    rng = np.random.default_rng(0)
    values_dict = {
        "stochastic (A)": [
            rng.normal(100, variance, size=n_iters - offset)
            / np.arange(offset, n_iters)
            for variance, offset in zip(
                rng.integers(0.5, 5, size=20), (rng.integers(5, 300, size=20))
            )
        ],
        "stochastic (S)": [
            rng.normal(100, variance, size=n_iters - offset)
            / (np.arange(offset, n_iters) ** 1.5)
            for variance, offset in zip(
                rng.integers(0.5, 5, size=20), (rng.integers(5, 300, size=20))
            )
        ],
        "deterministic (A)": [
            rng.normal(100, 1, size=n_iters - 2) / (np.arange(2, n_iters) ** 2)
        ],
        "deterministic (S)": [
            rng.normal(100, 1, size=n_iters - 2) / (np.arange(2, n_iters) ** 2.5)
        ],
    }

    plot(
        n_iters,
        values_dict,
        save_name=f"minimal_working_example",
    )


问:
Geolocation for the 'Port of Dalian' returning empty response for Here-Map Api
We are using reverse geocode api from Here-Map for getting details of specific geolocation. It is actually working for most of the geo-cordinates, but not for location 'Port of Dalian' with geocode 38.999712, 121.886565

We have gone through the documentation as well - https://developer.here.com/documentation/examples/rest/geocoder/reverse-geocode. But for the geocode it is not returning anything, but Google map works fine for the geocodes.

We have tried with other some Geocodes(-19.015438, 29.154857), and its working, but not for this. We are getting country details for other Geocodes. How could we be able to get details for this Geocodes, or get it updated with the maps.


问:
List all customers with active subscriptions
What i would like to do is have a list with all the customers on my website who has an active subscription with the WooCommerce Subscriptions plugin.

I would really appreciate your help with this. I have searched the internet without finding a solution.

I have tried to find a way in Woocommerce Subscriptions Developer Docs without success. I have tried creating different shortcodes but none seem to be working. Here is one example found here: Get active members list for a subscription plan in Woocommerce subscriptions (this returns an empty list with only the headings):

```<code>// The SQL query
function get_active_subscribers_for_plan( $product_id = 71164, $variation_id = 0 ) {
    global $wpdb;

    if( $variation_id > 0 ){
        $query_subscription_plan = "AND woim.meta_key = '_variation_id' AND woim.meta_value = '$variation_id'";
    } else {
        $query_subscription_plan = "AND woim.meta_key = '_product_id' AND woim.meta_value = '$product_id'";
    }

    $results = $wpdb->get_results( "
        SELECT DISTINCT pm1.meta_value as user_id, pm2.meta_value as first_name,
        pm3.meta_value as last_name, pm4.meta_value as phone, pm5.meta_value as email
        FROM {$wpdb->prefix}posts as p
        JOIN {$wpdb->prefix}postmeta as pm1 ON p.ID = pm1.post_id
        JOIN {$wpdb->prefix}postmeta as pm2 ON p.ID = pm2.post_id
        JOIN {$wpdb->prefix}postmeta as pm3 ON p.ID = pm3.post_id
        JOIN {$wpdb->prefix}postmeta as pm4 ON p.ID = pm4.post_id
        JOIN {$wpdb->prefix}postmeta as pm5 ON p.ID = pm5.post_id
        JOIN {$wpdb->prefix}posts as p2 ON p.ID = p2.post_parent
        JOIN {$wpdb->prefix}woocommerce_order_items as woi ON p2.ID = woi.order_id
        JOIN {$wpdb->prefix}woocommerce_order_itemmeta as woim ON woi.order_item_id = woim.order_item_id
        WHERE p.post_type = 'shop_order'
        AND p2.post_type = 'shop_subscription'
        AND p2.post_status = 'wc-active'
        AND pm1.meta_key = '_customer_user'
        AND pm2.meta_key = '_billing_first_name'
        AND pm3.meta_key = '_billing_last_name'
        AND pm4.meta_key = '_billing_phone'
        AND pm5.meta_key = '_billing_email'
        $query_subscription_plan
    ");

    return $results;
}

// The Html Output
function display_active_subscribers_for_plan( $product_id = 0, $variation_id = 0 ){
    // The query
    $results = get_active_subscribers_for_plan( $product_id, $variation_id );

    // The display
    echo '<table>
    <thead><tr>
        <th>' . __("User ID","woocommerce") . '</th>
        <th>' . __("First name","woocommerce") . '</th>
        <th>' . __("Last name","woocommerce") . '</th>
        <th>' . __("Phone","woocommerce") . '</th>
        <th>' . __("Email","woocommerce") . '</th>
    </tr></thead>
    <tbody>';
    // Loop through each subscriber
    foreach( $results as $result ){
        // Edit User Url
        $edit_user_url = home_url('/wp-admin/user-edit.php?user_id=' . $result->user_id . '/');

        echo '<tr>
        <td><a href="' . $edit_user_url . '">' . $result->user_id . '</a></td>
        <td>' . $result->first_name . '</td>
        <td>' . $result->last_name . '</td>
        <td>' . $result->phone . '</td>
        <td><a href="malto:' . $result->email . '">' . $result->email . '</a></td>
        </tr>';
    }
    echo '</tbody></table>';
}
</code>```

The problem with this is that it lists no subscribers.

I appreciate your help.

Thank you.

I tried this solution: Get active members list for a subscription plan in Woocommerce subscriptions

But i can not get it to work. Maybe i am calling the function incorrectly. Can someone please tell me how to call this in elementor. I am not that good in this, maybe this is basic but i cannot figure it out.

Body:
What i would like to do is have a list with all the customers on my website who has an active subscription with the WooCommerce Subscriptions plugin.

I would really appreciate your help with this. I have searched the internet without finding a solution.

I have tried to find a way in Woocommerce Subscriptions Developer Docs without success. I have tried creating different shortcodes but none seem to be working. Here is one example found here: Get active members list for a subscription plan in Woocommerce subscriptions (this returns an empty list with only the headings):

// The SQL query
function get_active_subscribers_for_plan( $product_id = 71164, $variation_id = 0 ) {
    global $wpdb;

    if( $variation_id > 0 ){
        $query_subscription_plan = "AND woim.meta_key = '_variation_id' AND woim.meta_value = '$variation_id'";
    } else {
        $query_subscription_plan = "AND woim.meta_key = '_product_id' AND woim.meta_value = '$product_id'";
    }

    $results = $wpdb->get_results( "
        SELECT DISTINCT pm1.meta_value as user_id, pm2.meta_value as first_name,
        pm3.meta_value as last_name, pm4.meta_value as phone, pm5.meta_value as email
        FROM {$wpdb->prefix}posts as p
        JOIN {$wpdb->prefix}postmeta as pm1 ON p.ID = pm1.post_id
        JOIN {$wpdb->prefix}postmeta as pm2 ON p.ID = pm2.post_id
        JOIN {$wpdb->prefix}postmeta as pm3 ON p.ID = pm3.post_id
        JOIN {$wpdb->prefix}postmeta as pm4 ON p.ID = pm4.post_id
        JOIN {$wpdb->prefix}postmeta as pm5 ON p.ID = pm5.post_id
        JOIN {$wpdb->prefix}posts as p2 ON p.ID = p2.post_parent
        JOIN {$wpdb->prefix}woocommerce_order_items as woi ON p2.ID = woi.order_id
        JOIN {$wpdb->prefix}woocommerce_order_itemmeta as woim ON woi.order_item_id = woim.order_item_id
        WHERE p.post_type = 'shop_order'
        AND p2.post_type = 'shop_subscription'
        AND p2.post_status = 'wc-active'
        AND pm1.meta_key = '_customer_user'
        AND pm2.meta_key = '_billing_first_name'
        AND pm3.meta_key = '_billing_last_name'
        AND pm4.meta_key = '_billing_phone'
        AND pm5.meta_key = '_billing_email'
        $query_subscription_plan
    ");

    return $results;
}

// The Html Output
function display_active_subscribers_for_plan( $product_id = 0, $variation_id = 0 ){
    // The query
    $results = get_active_subscribers_for_plan( $product_id, $variation_id );

    // The display
    echo '

        ' . __("User ID","woocommerce") . '
        ' . __("First name","woocommerce") . '
        ' . __("Last name","woocommerce") . '
        ' . __("Phone","woocommerce") . '
        ' . __("Email","woocommerce") . '

';
    // Loop through each subscriber
    foreach( $results as $result ){
        // Edit User Url
        $edit_user_url = home_url('/wp-admin/user-edit.php?user_id=' . $result->user_id . '/');

        echo '

        ' . $result->user_id . '
        ' . $result->first_name . '
        ' . $result->last_name . '
        ' . $result->phone . '
        email . '">' . $result->email . '

';
    }
    echo '

';
}

The problem with this is that it lists no subscribers.

I appreciate your help.

Thank you.

I tried this solution: Get active members list for a subscription plan in Woocommerce subscriptions

But i can not get it to work. Maybe i am calling the function incorrectly. Can someone please tell me how to call this in elementor. I am not that good in this, maybe this is basic but i cannot figure it out.


问:
How can I detect that Unity used error default shader through code?
Is there any way in Unity to know, that there is magenta error shader present in the scene via script? Like, can we really know through code, that material, rendered in scene is actually magenta pink and not one we wanted?

```<code>void Start()
{
    Renderer[] renderers = FindObjectsOfType<Renderer>();
    foreach (var renderer in renderers)
    {
        foreach (var mat in renderer.materials)
        {
            if (mat.shader.name == "Hidden/InternalErrorShader")
            {
                //message
                break;
            }
        }
    }
}
</code>```

This code always returns shader, assigned to an object in editor, not the default magenta error shader unity actually renders.

I expect a way to determine the magenta error shader is rendered not just by eyes, but with code

Body:
Is there any way in Unity to know, that there is magenta error shader present in the scene via script? Like, can we really know through code, that material, rendered in scene is actually magenta pink and not one we wanted?

void Start()
{
    Renderer[] renderers = FindObjectsOfType<Renderer>();
    foreach (var renderer in renderers)
    {
        foreach (var mat in renderer.materials)
        {
            if (mat.shader.name == "Hidden/InternalErrorShader")
            {
                //message
                break;
            }
        }
    }
}

This code always returns shader, assigned to an object in editor, not the default magenta error shader unity actually renders.

I expect a way to determine the magenta error shader is rendered not just by eyes, but with code


问:
REST API java program that accepts JSON POST and receives JSON data with free URI's
I want REST API code in java that accepts JSON which is passed in runtime and use POST method and get JSON response.

I require any free URI that where we can test all types of REST API programs and retreive all type of data


问:
Can I use only one redis connection for my django app?
Introduction:

django 3.2.16

django-redis 4.12.1

Problem: I use redis as a cache storage. I put the data to redis manually using the next code:

```<code>from django_redis import get_redis_connection

def redis_handler() -> None:
    redis = get_redis_connection()
    ...
    # some business logic
    ...
    redis.close()
</code>```

I call redis_handler() often and every time a new connection to redis created.

Idea/Solution:
Can I create a "global" redis connection once for a project and then import and use it everywhere?
Where I can do it? What problems can be? Because I will not close it while the project works.

I was inspired FastApi - it has hooks when the project starts and stops.

Body:
Introduction:

django 3.2.16

django-redis 4.12.1

Problem: I use redis as a cache storage. I put the data to redis manually using the next code:

from django_redis import get_redis_connection

def redis_handler() -> None:
    redis = get_redis_connection()
    ...
    # some business logic
    ...
    redis.close()

I call redis_handler() often and every time a new connection to redis created.

Idea/Solution:
Can I create a "global" redis connection once for a project and then import and use it everywhere?
Where I can do it? What problems can be? Because I will not close it while the project works.

I was inspired FastApi - it has hooks when the project starts and stops.


问:
Visual Studio Blend for Uno 4.x Projects
When I launch Visual Studio Blend 17.4.3 and open a just-created Uno project (.NET 7) then open a XAML document that's in the solution (MainPage.xaml), I see XAML in an editor--but I do not see any way to get to the design view and see the usual Blend features, such as a toolbox of controls (StackPanel, TextBox, etc.). Am I missing something?


问:
Inserting high-res pictures into Excel with VBA
I am trying to use VBA to insert a high-res picture into Excel.  When I insert it, the quality is awful.  I found that under File/Options/Advanced, I can set Default Resolution to 'High Fidelity' and 'Do not compress images in file'.  With these settings, I can insert a high resolution picture.

The problem is that I cannot find out how to turn these settings on via VBA.  I have tried using the Macro recorder, and it doesn't record anything. How do I enable these settings programmatically with a new file?


问:
Type CallerMemberNameAttribute exists in both System.Runtime 2.6.10 and mscorlib
I have a Class Library running on .Net 4.7. Attempting to upgrade this project to and SDK style i take the following steps in a terminal window (Im using Visual Studio 2022) and keep the target to 4.7

```<code>dotnet tool install --global Project2015To2017.Migrate2019.Tool

dotnet migrate-2019 wizard proj.csproj
</code>```

(Received an error about the runtime not being installed on my machine so clicked the link and installed.)

I get some messages but no real errors as such e.g.

A better way to reference 'System.ComponentModel.Composition' assembly is using respective 'System.ComponentModel.Composition' NuGet package. It will simplify porting to other runtimes and enable possible .NET SDK tooling improvements.

and

Consider migrating to 'portable' debug type, cross-platform alternative to legacy Windows PDBs.

Number of these types of messages appear.

I load up the solution in VS 2022 and try to rebuild but some NuGet package errors occur so i restore all packages using the Nuget restore command.

Im now faced with the error

The type 'CallerMemberNameAttribute' exists in both System.Runtime VErsion 2.6.10.0 and mscorlib Version 4.0.0.0

This occurs on the line

```<code>public void DoSomething([CallerMemberName] string nm = "")
{}
</code>```

Ive tried to reference this explicitly i.e. System.Runtime.CompilerServices.CallerMemberName but that didnt work and not entirely sure what i could attempt to resolve this?

Body:
I have a Class Library running on .Net 4.7. Attempting to upgrade this project to and SDK style i take the following steps in a terminal window (Im using Visual Studio 2022) and keep the target to 4.7

dotnet tool install --global Project2015To2017.Migrate2019.Tool

dotnet migrate-2019 wizard proj.csproj

(Received an error about the runtime not being installed on my machine so clicked the link and installed.)

I get some messages but no real errors as such e.g.

A better way to reference 'System.ComponentModel.Composition' assembly is using respective 'System.ComponentModel.Composition' NuGet package. It will simplify porting to other runtimes and enable possible .NET SDK tooling improvements.

and

Consider migrating to 'portable' debug type, cross-platform alternative to legacy Windows PDBs.

Number of these types of messages appear.

I load up the solution in VS 2022 and try to rebuild but some NuGet package errors occur so i restore all packages using the Nuget restore command.

Im now faced with the error

The type 'CallerMemberNameAttribute' exists in both System.Runtime VErsion 2.6.10.0 and mscorlib Version 4.0.0.0

This occurs on the line

public void DoSomething([CallerMemberName] string nm = "")
{}

Ive tried to reference this explicitly i.e. System.Runtime.CompilerServices.CallerMemberName but that didnt work and not entirely sure what i could attempt to resolve this?


问:
Asp .net core- Modal dialog keeps closing when i click inside the Modal dialog box
I'm working on asp .net core application. I need to load a modal dialog box when the page loads based on data and fetch some input from users. I'm able to load the popup using the following jquery code

```<code> $('#activePolicyChooserDialog').modal({ backdrop: "static ", keyboard: false }, 'show');
</code>```

when I click an element(radio button) inside the popup it keeps closing how can I prevent the popup from closing when I click the radio button inside the popup

```<code><div class="modal container w-100" id="id">
 <div class="modal-dialog modal-lg bg-white">
    <div class="modal-body modal-xl">
            @foreach (var x in Ids)
            {
                <div class="row">
                    <input class="col-1 mt-3" style="height: 20px; width: 20px; vertical-align: top;"  type="radio" name="option`your text`" value="@x.id" />
                    <table class="table table-sm table-striped col-10 rounded">
                        <thead class="card-header section-header">
                            <tr style="font-family: Oxygen-Bold, 'Oxygen Bold', Oxygen, sans-serif; font-weight: 700;">
                                <th colspan="4">Package#: @x.SubmissionIdNo</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr style="    font-family: 'Lato Bold', Lato, sans-serif;font-weight: 700;">
                                <td>Product</td>
                                <td>Policy#</td>
                                <td>Effective Date</td>
                                <td></td>
                            </tr>
                            @foreach (var item in Model.Where(_ => _.id == x.id))
                            {
                                <tr style="font-family: Lato, sans-serif; font-weight: 400;">
                                    <td>@item.Name</td>
                                    <td> @item.Number  </td>
                                    <td>@item.Date.ToShortDateString()</td>
                                    <td></td>
                                </tr>
                            }
                        </tbody>
                    </table>
                </div>
            }

            <button type="button" class="btn btn-primary m-3" id="selectPackageBtn">Select</button>
    </div>
    </div>
 </div>
</code>```

I don't want the pop up to close when I click on the radio button and be able to call the respective jquery event handlers

Body:
I'm working on asp .net core application. I need to load a modal dialog box when the page loads based on data and fetch some input from users. I'm able to load the popup using the following jquery code

 $('#activePolicyChooserDialog').modal({ backdrop: "static ", keyboard: false }, 'show');

when I click an element(radio button) inside the popup it keeps closing how can I prevent the popup from closing when I click the radio button inside the popup

            @foreach (var x in Ids)
            {

                    <input class="col-1 mt-3" style="height: 20px; width: 20px; vertical-align: top;"  type="radio" name="option`your text`" value="@x.id" />

                                Package#: @x.SubmissionIdNo

                                Product
                                Policy#
                                Effective Date

                            @foreach (var item in Model.Where(_ => _.id == x.id))
                            {

                                    @item.Name
                                     @item.Number
                                    @item.Date.ToShortDateString()

                            }

            }

            <button type="button" class="btn btn-primary m-3" id="selectPackageBtn">Select</button>

I don't want the pop up to close when I click on the radio button and be able to call the respective jquery event handlers


问:
My Animation does only render the Background plane
I´ve got a strange situation.

I´ve created this Animation with Blender:

https://lootziffers-welt.de/Animation.zip

now if i try to render it i only get the background plane rendered.
as if the images where not there -.-

May somebody tell me what im doing wrong here?