问:
Is copy() still needed for extracting a subset of a pandas dataframe?
In the codebase I'm working in, I see the following

```<code>df1 = some pandas dataframe (one of the columns is quantity)
df1_subset = df1[df1.quantity == input_quantity].copy()
</code>```

I am wondering why the .copy() is needed here? Doesn't df1_subset = df1[df1.quantity == input_quantity] make df1_subset a copy and not a reference?

I saw in why should I make a copy of a data frame in pandas that a reference would be returned, but I think this is outdated?

Body:
In the codebase I'm working in, I see the following

df1 = some pandas dataframe (one of the columns is quantity)
df1_subset = df1[df1.quantity == input_quantity].copy()

I am wondering why the .copy() is needed here? Doesn't df1_subset = df1[df1.quantity == input_quantity] make df1_subset a copy and not a reference?

I saw in why should I make a copy of a data frame in pandas that a reference would be returned, but I think this is outdated?


来源: stackexchange

问:
How to use the Microsoft.Extensions.Logging.ApplicationInsights package to create an ILogger instance for AppInsights inside a .NET Framework WebForms
We are having a .NET 4.7.2 WebForms project that needs to consume a library. That library is also consumed by another application which is based on the Core platform i.e. .NET 6.0

We want to pass an ILogger instance to the library class from both Framework side and Core side. In the Framework side, we are able to create ILogger instance using the Microsoft.Extensions.Logging package and below code.

```<code>    var serviceCollection = new ServiceCollection();
    serviceCollection.AddLogging();
    var serviceProvider = serviceCollection.BuildServiceProvider();
    ILogger logger = serviceProvider.GetService<ILogger>();
</code>```

But how do we pass the App Insights and Event Viewer providers to this logger from .NET Framework WebForms?

ContentLicense: CC BY-SA 4.0

Body:
We are having a .NET 4.7.2 WebForms project that needs to consume a library. That library is also consumed by another application which is based on the Core platform i.e. .NET 6.0

We want to pass an ILogger instance to the library class from both Framework side and Core side. In the Framework side, we are able to create ILogger instance using the Microsoft.Extensions.Logging package and below code.

    var serviceCollection = new ServiceCollection();
    serviceCollection.AddLogging();
    var serviceProvider = serviceCollection.BuildServiceProvider();
    ILogger logger = serviceProvider.GetService<ILogger>();

But how do we pass the App Insights and Event Viewer providers to this logger from .NET Framework WebForms?


问:
Error log for null values in application Engine PeopleSoft
I have the requirement that the BUSINESS_UNIT field needs to be updated in the Voucher tables(VCHR_LINE_STG), I'm writing SQL in SQL action in the application engine After the update statement, the results are returning the null values.
The total process is not running. How can we handle null Values?

Will PeopleCode work for this scenario? If works which code will work for Null values

Table name: VCHR_LINE_STG,
Field name: BUSINESS_UNIT.

Thanks


问:
Next - Hydrating translations with next-i18next on client site
I have a problem with hydratation of translations via API.
I am using only two namespaces. common.json and paths.json
and if i change some of the translation in database for namespace common, it change whole namespace and it cause to revalid all of the pages. So it is not very well optimized.

```<code>export const getStaticProps = async ({ locale }: GetServerSidePropsContext) => {
   try {
     return {
       props: {
         ...(await serverSideTranslations(locale as any, i18config?.options?.ns))
       },
       revalidate: REVALIDATE.ONE_DAY
     }
    } catch (e) {
       ...
    }
}
</code>```

Is there any options to rehydrate translations on client site, after server send html to client? Or can next18next detect the only changed key of translation and rehydrate only page which using actual key?

I really hope there is another solution then split all namespaces by pages.

I want to rehydrate "serverside" translation runtime on client site. It seems to be the best solution for me so far.

Body:
I have a problem with hydratation of translations via API.
I am using only two namespaces. common.json and paths.json
and if i change some of the translation in database for namespace common, it change whole namespace and it cause to revalid all of the pages. So it is not very well optimized.

export const getStaticProps = async ({ locale }: GetServerSidePropsContext) => {
   try {
     return {
       props: {
         ...(await serverSideTranslations(locale as any, i18config?.options?.ns))
       },
       revalidate: REVALIDATE.ONE_DAY
     }
    } catch (e) {
       ...
    }
}

Is there any options to rehydrate translations on client site, after server send html to client? Or can next18next detect the only changed key of translation and rehydrate only page which using actual key?

I really hope there is another solution then split all namespaces by pages.

I want to rehydrate "serverside" translation runtime on client site. It seems to be the best solution for me so far.


问:
R: making plot title align with str_wrap
I had very long variable names, and I managed to align them nicely by using str_wrap. But where in this code I should apply the same method to make the plot title align?

This did not work.

```<code>scale_y_discrete(labels = function(x)str_wrap(x, width = 20))
</code>```

I don't get the idea of this function(x).

```<code>ggplot(remove_missing(plotdata), mapping = aes(x = value, y = pct)) +
  geom_col(aes(fill = value),
           width = 0.30) +
  scale_y_continuous(
    breaks = seq(from = 0, to = 1, by = 0.2),
    minor_breaks = seq(from = 0, to = 1, by = 0.1),
    labels = seq(from = 0, to = 100, by = 20),
    limits = c(0, 1),
    expand = c(0, 0)) +
  scale_fill_manual(
    values = c('option1' = "blue",
               'option2' = "blue",
               'option3' = "blue",
               'option4' = "blue",
               'option5' = "blue",
               'option6' = "blue"),
    drop = FALSE) +
  labs(x = "", y = "% of responders") +
  guides(fill = "none") +
  theme(
    plot.margin = margin(t = 50, r =  30, b = 20, l = 5.5),
    plot.title = element_text(size = 15, face = "plain"),
    panel.background = element_blank(),
    panel.grid.major = element_line(colour = "grey"),
    panel.grid.major.x = element_blank(),
    panel.grid.minor = element_line(colour = "lightgrey"),
    axis.ticks.x = element_blank(),
    axis.ticks.y = element_line(colour = "grey"),
    axis.text.y = element_text(
      size = 11,
      face = "plain",
      hjust = 0
    ),
    axis.text.x = element_text(
      size = 11,
      face = "bold",
      hjust = 0
    ),
    axis.title.x = element_text(size = 15),
  ) +
  coord_flip() +
  ggtitle("This title is way too long and all of it does not fit into the plot, I mean it is way too long") +
  scale_x_discrete(labels = function(x)
    str_wrap(x, width = 20))
</code>```

Data for the plot

```<code>plotdata <- structure(list(variable = c("item78", "item79", "item80", "item81",
"item82", "item83", "item84", "option1", "option1", "option2",
"option2", "option3", "option3", "option4", "option4", "option5",
"option5", "option6", "option6"), value = structure(c(NA, NA,
NA, NA, NA, NA, NA, 2L, NA, 5L, NA, 1L, NA, 3L, NA, 6L, NA, 4L,
NA), .Label = c("option3", "option1", "option4", "option6", "option2",
"option5"), class = c("ordered", "factor")), n = c(147L, 147L,
147L, 147L, 147L, 147L, 147L, 98L, 49L, 133L, 14L, 50L, 97L,
98L, 49L, 138L, 9L, 103L, 44L), pct = c(1, 1, 1, 1, 1, 1, 1,
0.666666666666667, 0.333333333333333, 0.904761904761905, 0.0952380952380952,
0.340136054421769, 0.659863945578231, 0.666666666666667, 0.333333333333333,
0.938775510204082, 0.0612244897959184, 0.700680272108844, 0.299319727891156
)), row.names = c(NA, -19L), groups = structure(list(variable = c("item78",
"item79", "item80", "item81", "item82", "item83", "item84", "option1",
"option2", "option3", "option4", "option5", "option6"), .rows = structure(list(
    1L, 2L, 3L, 4L, 5L, 6L, 7L, 8:9, 10:11, 12:13, 14:15, 16:17,
    18:19), ptype = integer(0), class = c("vctrs_list_of", "vctrs_vctr",
"list"))), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-13L), .drop = TRUE), class = c("grouped_df", "tbl_df", "tbl",
"data.frame"))
</code>```

Body:
I had very long variable names, and I managed to align them nicely by using str_wrap. But where in this code I should apply the same method to make the plot title align?

This did not work.

scale_y_discrete(labels = function(x)str_wrap(x, width = 20))

I don't get the idea of this function(x).

ggplot(remove_missing(plotdata), mapping = aes(x = value, y = pct)) +
  geom_col(aes(fill = value),
           width = 0.30) +
  scale_y_continuous(
    breaks = seq(from = 0, to = 1, by = 0.2),
    minor_breaks = seq(from = 0, to = 1, by = 0.1),
    labels = seq(from = 0, to = 100, by = 20),
    limits = c(0, 1),
    expand = c(0, 0)) +
  scale_fill_manual(
    values = c('option1' = "blue",
               'option2' = "blue",
               'option3' = "blue",
               'option4' = "blue",
               'option5' = "blue",
               'option6' = "blue"),
    drop = FALSE) +
  labs(x = "", y = "% of responders") +
  guides(fill = "none") +
  theme(
    plot.margin = margin(t = 50, r =  30, b = 20, l = 5.5),
    plot.title = element_text(size = 15, face = "plain"),
    panel.background = element_blank(),
    panel.grid.major = element_line(colour = "grey"),
    panel.grid.major.x = element_blank(),
    panel.grid.minor = element_line(colour = "lightgrey"),
    axis.ticks.x = element_blank(),
    axis.ticks.y = element_line(colour = "grey"),
    axis.text.y = element_text(
      size = 11,
      face = "plain",
      hjust = 0
    ),
    axis.text.x = element_text(
      size = 11,
      face = "bold",
      hjust = 0
    ),
    axis.title.x = element_text(size = 15),
  ) +
  coord_flip() +
  ggtitle("This title is way too long and all of it does not fit into the plot, I mean it is way too long") +
  scale_x_discrete(labels = function(x)
    str_wrap(x, width = 20))

Data for the plot

plotdata <- structure(list(variable = c("item78", "item79", "item80", "item81",
"item82", "item83", "item84", "option1", "option1", "option2",
"option2", "option3", "option3", "option4", "option4", "option5",
"option5", "option6", "option6"), value = structure(c(NA, NA,
NA, NA, NA, NA, NA, 2L, NA, 5L, NA, 1L, NA, 3L, NA, 6L, NA, 4L,
NA), .Label = c("option3", "option1", "option4", "option6", "option2",
"option5"), class = c("ordered", "factor")), n = c(147L, 147L,
147L, 147L, 147L, 147L, 147L, 98L, 49L, 133L, 14L, 50L, 97L,
98L, 49L, 138L, 9L, 103L, 44L), pct = c(1, 1, 1, 1, 1, 1, 1,
0.666666666666667, 0.333333333333333, 0.904761904761905, 0.0952380952380952,
0.340136054421769, 0.659863945578231, 0.666666666666667, 0.333333333333333,
0.938775510204082, 0.0612244897959184, 0.700680272108844, 0.299319727891156
)), row.names = c(NA, -19L), groups = structure(list(variable = c("item78",
"item79", "item80", "item81", "item82", "item83", "item84", "option1",
"option2", "option3", "option4", "option5", "option6"), .rows = structure(list(
    1L, 2L, 3L, 4L, 5L, 6L, 7L, 8:9, 10:11, 12:13, 14:15, 16:17,
    18:19), ptype = integer(0), class = c("vctrs_list_of", "vctrs_vctr",
"list"))), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-13L), .drop = TRUE), class = c("grouped_df", "tbl_df", "tbl",
"data.frame"))


问:
Publish an NPM Package with dependencies
I am trying to publish an npm package. My index.js requires Axios, so Axios is installed as a dependency and I have a node_modules file. I am testing locally with npm link and everything works fine.

My question is while publishing to the npm registry, do I ignore the node modules folder and publish my index.js, package-lock.json, and package.json? Do I have to run any other command before running npm publish? I saw some examples that say npm build before npm publish


问:
Multiple domains for CORS
Following this - https://www.ibm.com/support/pages/configuring-cors-websphere-application-server - I am trying to configure Apache for multiple origin domains and it isn't working. I have the following:

```<code><IfModule setenvif_module>
    SetEnvIfNoCase                  Origin "https?://(dev.mydomain.com|qa.mydomain.com|mydomain.com|myotherdomain.com|www.myotherdomain.com)(:\d+)?$" ACAO=$0
    SetEnvIfNoCase                  REQUEST_METHOD OPTIONS skipwas=1
</IfModule>

<IfModule headers_module>
    Header                          onsuccess unset Access-Control-Allow-origin env=ACAO
    Header                          always set Access-Control-Allow-Origin "%{ACAO}e" env=ACAO
    Header                          always append Vary "Origin"
</IfModule>
</code>```

This results in a no ACAO header present in the logs when I open up the Chrome console and attempt to fetch from any of the present domains. Just wondering what I'm doing wrong?

Title: Multiple domains for CORS

Body:
Following this - https://www.ibm.com/support/pages/configuring-cors-websphere-application-server - I am trying to configure Apache for multiple origin domains and it isn't working. I have the following:

<IfModule setenvif_module>
    SetEnvIfNoCase                  Origin "https?://(dev.mydomain.com|qa.mydomain.com|mydomain.com|myotherdomain.com|www.myotherdomain.com)(:\d+)?$" ACAO=$0
    SetEnvIfNoCase                  REQUEST_METHOD OPTIONS skipwas=1
</IfModule>

<IfModule headers_module>
    Header                          onsuccess unset Access-Control-Allow-origin env=ACAO
    Header                          always set Access-Control-Allow-Origin "%{ACAO}e" env=ACAO
    Header                          always append Vary "Origin"
</IfModule>

This results in a no ACAO header present in the logs when I open up the Chrome console and attempt to fetch from any of the present domains. Just wondering what I'm doing wrong?


问:
Raw response data different than response from requests
I am getting a different response using the requests library in python compared to the raw response data shown in chrome dev tools.

The page: https://www.gerflor.co.uk/professionals-products/floors/taralay-impression-control.html

When clicking on the colour filter options for say the colour 'Brown light', a request appears in the network tab 'get-colors.html'. I have replicated this request with the appropriate headers and payload, yet I am getting a different response.

The response in the dev tools shows a json response, but when making this request in python I am getting a transparent web page. Even clicking on the file to open in a new tab from the dev tools opens up a transparent web page rather than the json response I am looking for. It seems as if this response is only exclusive to viewing it within the dev tools, and I cannot figure out how to recreate this request for the desired response.

Here is what I have done:

```<code>import requests
import json

url = ("https://www.gerflor.co.uk/colors-enhancer/get-colors.html")

headers = {'accept': 'application/json, text/plain, */*', 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8', 'cache-control': 'no-cache', 'content-length': '72', 'content-type': 'application/json;charset=UTF-8', 'cookie': '_ga=GA1.3.1278783742.1660305222; _hjSessionUser_1471753=eyJpZCI6IjU5OWIyOTJjLTZkM2ItNThiNi1iYzI4LTAzMDA0ZmVhYzFjZSIsImNyZWF0ZWQiOjE2NjAzMDUyMjIzMzksImV4aXN0aW5nIjp0cnVlfQ==; ln_or=eyI2NTM1MSI6ImQifQ%3D%3D; valid_navigation=1; tarteaucitron=!hotjar=true!googletagmanager=true; _gid=GA1.3.1938727070.1673437106; cc_cookie_accept=cc_cookie_accept; fuel_csrf_token=78fd0611d0719f24c2b40f49fab7ccc13f7623d7b9350a97cd81b93695a6febf695420653980ff9cb210e383896f5978f0becffda036cf0575a1ce0ff4d7f5b5; _hjIncludedInSessionSample=0; _hjSession_1471753=eyJpZCI6IjA2ZTg5YjgyLWUzNTYtNDRkZS1iOWY4LTA1OTI2Yjg0Mjk0OCIsImNyZWF0ZWQiOjE2NzM0NDM1Njg1MjEsImluU2FtcGxlIjpmYWxzZX0=; _hjIncludedInPageviewSample=1; _hjAbsoluteSessionInProgress=0; fuelfid=arY7ozatUQWFOvY0HgkmZI8qYSa1FPLDmxHaLIrgXxwtF7ypHdBPuVtgoCbjTLu4_bELQd33yf9brInne0Q0SmdvR1dPd1VoaDEyaXFmZFlxaS15ZzdZcDliYThkU0gyVGtXdXQ5aVFDdVk; _gat_UA-2144775-3=1', 'origin': 'https://www.gerflor.co.uk', 'pragma': 'no-cache', 'referer': 'https://www.gerflor.co.uk/professionals-products/floors/taralay-impression-control.html', 'sec-ch-ua': '"Not?A_Brand";v="8", "Chromium";v="108", "Google Chrome";v="108"', 'sec-ch-ua-mobile': '?0', 'sec-ch-ua-platform': '"Windows"', 'sec-fetch-dest': 'empty', 'sec-fetch-mode': 'cors', 'sec-fetch-site': 'same-origin', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36'}

payload = {'decors': [], 'shades': ['10020302'], 'designs': [], 'productId': '100031445'}

response = requests.post(url, headers=headers, data=payload)
</code>```

I should be getting a json response from here but instead I am only getting html text of a transparent web page. I have tried using response = requests.Session() and attempt to make the post request that way but still the same result.

Anyone have any insight as to why this is happening and what can be done to resolve this?

Thank you.

Body:
I am getting a different response using the requests library in python compared to the raw response data shown in chrome dev tools.

The page: https://www.gerflor.co.uk/professionals-products/floors/taralay-impression-control.html

When clicking on the colour filter options for say the colour 'Brown light', a request appears in the network tab 'get-colors.html'. I have replicated this request with the appropriate headers and payload, yet I am getting a different response.

The response in the dev tools shows a json response, but when making this request in python I am getting a transparent web page. Even clicking on the file to open in a new tab from the dev tools opens up a transparent web page rather than the json response I am looking for. It seems as if this response is only exclusive to viewing it within the dev tools, and I cannot figure out how to recreate this request for the desired response.

Here is what I have done:

import requests
import json

url = ("https://www.gerflor.co.uk/colors-enhancer/get-colors.html")

headers = {'accept': 'application/json, text/plain, */*', 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8', 'cache-control': 'no-cache', 'content-length': '72', 'content-type': 'application/json;charset=UTF-8', 'cookie': '_ga=GA1.3.1278783742.1660305222; _hjSessionUser_1471753=eyJpZCI6IjU5OWIyOTJjLTZkM2ItNThiNi1iYzI4LTAzMDA0ZmVhYzFjZSIsImNyZWF0ZWQiOjE2NjAzMDUyMjIzMzksImV4aXN0aW5nIjp0cnVlfQ==; ln_or=eyI2NTM1MSI6ImQifQ%3D%3D; valid_navigation=1; tarteaucitron=!hotjar=true!googletagmanager=true; _gid=GA1.3.1938727070.1673437106; cc_cookie_accept=cc_cookie_accept; fuel_csrf_token=78fd0611d0719f24c2b40f49fab7ccc13f7623d7b9350a97cd81b93695a6febf695420653980ff9cb210e383896f5978f0becffda036cf0575a1ce0ff4d7f5b5; _hjIncludedInSessionSample=0; _hjSession_1471753=eyJpZCI6IjA2ZTg5YjgyLWUzNTYtNDRkZS1iOWY4LTA1OTI2Yjg0Mjk0OCIsImNyZWF0ZWQiOjE2NzM0NDM1Njg1MjEsImluU2FtcGxlIjpmYWxzZX0=; _hjIncludedInPageviewSample=1; _hjAbsoluteSessionInProgress=0; fuelfid=arY7ozatUQWFOvY0HgkmZI8qYSa1FPLDmxHaLIrgXxwtF7ypHdBPuVtgoCbjTLu4_bELQd33yf9brInne0Q0SmdvR1dPd1VoaDEyaXFmZFlxaS15ZzdZcDliYThkU0gyVGtXdXQ5aVFDdVk; _gat_UA-2144775-3=1', 'origin': 'https://www.gerflor.co.uk', 'pragma': 'no-cache', 'referer': 'https://www.gerflor.co.uk/professionals-products/floors/taralay-impression-control.html', 'sec-ch-ua': '"Not?A_Brand";v="8", "Chromium";v="108", "Google Chrome";v="108"', 'sec-ch-ua-mobile': '?0', 'sec-ch-ua-platform': '"Windows"', 'sec-fetch-dest': 'empty', 'sec-fetch-mode': 'cors', 'sec-fetch-site': 'same-origin', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36'}

payload = {'decors': [], 'shades': ['10020302'], 'designs': [], 'productId': '100031445'}

response = requests.post(url, headers=headers, data=payload)

I should be getting a json response from here but instead I am only getting html text of a transparent web page. I have tried using response = requests.Session() and attempt to make the post request that way but still the same result.

Anyone have any insight as to why this is happening and what can be done to resolve this?

Thank you.


问:
Debug StackOverflow Exception in ASP .NET Core
I'm building an ASP .NET Core MVC app, and I started encountering a random StackOverflowException, it happens when the aplication is idle rather than when I perform an Http request, so I'm having a hard time finding where the problem might be. I have the stack trace, and I see a recursion that should be whats causing the call stack to overflow, but it is from a method from framework itself, so I can't find the underlying cause.

I tried simplifying my ViewModels using DTOs instead of model objects, and at first it looked like it was working, the app was working 8 hours without crashing with the StackOverflowException (normally it happened 10-15 minutes from when I started the app), but now it started happening again, here is my call stack:

```<code>>   System.Private.CoreLib.dll!System.ModuleHandle.ResolveMethod(System.Runtime.CompilerServices.QCallModule module, int methodToken, System.IntPtr* typeInstArgs, int typeInstCount, System.IntPtr* methodInstArgs, int methodInstCount)
    System.Private.CoreLib.dll!System.ModuleHandle.ResolveMethodHandleInternal(System.Reflection.RuntimeModule module, int methodToken, System.IntPtr[] typeInstantiationContext, int typeInstCount, System.IntPtr[] methodInstantiationContext, int methodInstCount) Línea 1405
    System.Private.CoreLib.dll!System.ModuleHandle.ResolveMethodHandle(int methodToken, System.RuntimeTypeHandle[] typeInstantiationContext, System.RuntimeTypeHandle[] methodInstantiationContext) Línea 1390
    System.Private.CoreLib.dll!System.RuntimeType.GetMethodBase(System.Reflection.RuntimeModule scope, int typeMetadataToken) Línea 1743
    System.Private.CoreLib.dll!System.Reflection.RuntimeCustomAttributeData.RuntimeCustomAttributeData(System.Reflection.RuntimeModule scope, System.Reflection.MetadataToken caCtorToken, System.Reflection.ConstArray blob) Línea 273
    System.Private.CoreLib.dll!System.Reflection.RuntimeCustomAttributeData.GetCustomAttributes(System.Reflection.RuntimeModule module, int tkTarget) Línea 213
    System.Private.CoreLib.dll!System.Reflection.RuntimeCustomAttributeData.GetCustomAttributesInternal(System.RuntimeType target) Línea 22
    System.Private.CoreLib.dll!System.Reflection.CustomAttributeData.GetCustomAttributes(System.Reflection.MemberInfo target) Línea 18
    Microsoft.Extensions.Logging.dll!Microsoft.Extensions.Logging.ProviderAliasUtilities.GetAlias(System.Type providerType)
    Microsoft.Extensions.Logging.dll!Microsoft.Extensions.Logging.LoggerRuleSelector.Select(Microsoft.Extensions.Logging.LoggerFilterOptions options, System.Type providerType, string category, out Microsoft.Extensions.Logging.LogLevel? minLevel, out System.Func<string, string, Microsoft.Extensions.Logging.LogLevel, bool> filter)
    Microsoft.Extensions.Logging.dll!Microsoft.Extensions.Logging.LoggerFactory.ApplyFilters(Microsoft.Extensions.Logging.LoggerInformation[] loggers)
    Microsoft.Extensions.Logging.dll!Microsoft.Extensions.Logging.LoggerFactory.RefreshFilters(Microsoft.Extensions.Logging.LoggerFilterOptions filterOptions)
    Microsoft.Extensions.Options.dll!Microsoft.Extensions.Options.OptionsMonitorExtensions.OnChange.AnonymousMethod__0(System.__Canon o, string _)
    Microsoft.Extensions.Options.dll!Microsoft.Extensions.Options.OptionsMonitor<System.__Canon>.ChangeTrackerDisposable.OnChange(System.__Canon options, string name)
    Microsoft.Extensions.Options.dll!Microsoft.Extensions.Options.OptionsMonitor<Microsoft.Extensions.Logging.LoggerFilterOptions>.InvokeChanged(string name)
    Microsoft.Extensions.Options.dll!Microsoft.Extensions.Options.OptionsMonitor<System.__Canon>..ctor.AnonymousMethod__6_2(string name)
    Microsoft.Extensions.Primitives.dll!Microsoft.Extensions.Primitives.ChangeToken.ChangeTokenRegistration<string>.OnChangeTokenFired()
    Microsoft.Extensions.Primitives.dll!Microsoft.Extensions.Primitives.ChangeToken.ChangeTokenRegistration<string>.RegisterChangeTokenCallback.AnonymousMethod__7_0(object s)
    System.Private.CoreLib.dll!System.Threading.CancellationTokenSource.Invoke(System.Delegate d, object state, System.Threading.CancellationTokenSource source) Línea 902
    System.Private.CoreLib.dll!System.Threading.CancellationTokenSource.CallbackNode.ExecuteCallback.AnonymousMethod__9_0(object s) Línea 1139
    System.Private.CoreLib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) Línea 183
    System.Private.CoreLib.dll!System.Threading.CancellationTokenSource.CallbackNode.ExecuteCallback() Línea 1141
    System.Private.CoreLib.dll!System.Threading.CancellationTokenSource.ExecuteCallbackHandlers(bool throwOnFirstException) Línea 722
    System.Private.CoreLib.dll!System.Threading.CancellationTokenSource.NotifyCancellation(bool throwOnFirstException) Línea 639
    System.Private.CoreLib.dll!System.Threading.CancellationTokenSource.Cancel() Línea 221
    Microsoft.Extensions.Configuration.dll!Microsoft.Extensions.Configuration.ConfigurationManager.RaiseChanged()
    Microsoft.Extensions.Configuration.dll!Microsoft.Extensions.Configuration.ConfigurationManager.AddSource.AnonymousMethod__1()
    Microsoft.Extensions.Primitives.dll!Microsoft.Extensions.Primitives.ChangeToken.OnChange.AnonymousMethod__0_0(System.Action callback)
    Microsoft.Extensions.Primitives.dll!Microsoft.Extensions.Primitives.ChangeToken.ChangeTokenRegistration<System.Action>.OnChangeTokenFired()
    Microsoft.Extensions.Primitives.dll!Microsoft.Extensions.Primitives.ChangeToken.ChangeTokenRegistration<System.Action>.RegisterChangeTokenCallback.AnonymousMethod__7_0(object s)
    System.Private.CoreLib.dll!System.Threading.CancellationTokenSource.Invoke(System.Delegate d, object state, System.Threading.CancellationTokenSource source) Línea 902
    System.Private.CoreLib.dll!System.Threading.CancellationTokenSource.CallbackNode.ExecuteCallback.AnonymousMethod__9_0(object s) Línea 1139
    System.Private.CoreLib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) Línea 183
    System.Private.CoreLib.dll!System.Threading.CancellationTokenSource.CallbackNode.ExecuteCallback() Línea 1141
    System.Private.CoreLib.dll!System.Threading.CancellationTokenSource.ExecuteCallbackHandlers(bool throwOnFirstException) Línea 722
    System.Private.CoreLib.dll!System.Threading.CancellationTokenSource.NotifyCancellation(bool throwOnFirstException) Línea 639
    System.Private.CoreLib.dll!System.Threading.CancellationTokenSource.Cancel() Línea 221
    Microsoft.Extensions.Configuration.dll!Microsoft.Extensions.Configuration.ConfigurationProvider.OnReload()
    Microsoft.Extensions.Configuration.FileExtensions.dll!Microsoft.Extensions.Configuration.FileConfigurationProvider.Load(bool reload)
    Microsoft.Extensions.Configuration.FileExtensions.dll!Microsoft.Extensions.Configuration.FileConfigurationProvider..ctor.AnonymousMethod__1_1()
    Microsoft.Extensions.Primitives.dll!Microsoft.Extensions.Primitives.ChangeToken.OnChange.AnonymousMethod__0_0(System.Action callback)
    Microsoft.Extensions.Primitives.dll!Microsoft.Extensions.Primitives.ChangeToken.ChangeTokenRegistration<System.Action>.OnChangeTokenFired()
    Microsoft.Extensions.Primitives.dll!Microsoft.Extensions.Primitives.ChangeToken.ChangeTokenRegistration<System.Action>.RegisterChangeTokenCallback.AnonymousMethod__7_0(object s)
    System.Private.CoreLib.dll!System.Threading.CancellationTokenSource.Invoke(System.Delegate d, object state, System.Threading.CancellationTokenSource source) Línea 902
    System.Private.CoreLib.dll!System.Threading.CancellationTokenSource.Register(System.Delegate callback, object stateForCallback, System.Threading.SynchronizationContext syncContext, System.Threading.ExecutionContext executionContext) Línea 610
    System.Private.CoreLib.dll!System.Threading.CancellationToken.Register(System.Delegate callback, object state, bool useSynchronizationContext, bool useExecutionContext) Línea 290
    System.Private.CoreLib.dll!System.Threading.CancellationToken.UnsafeRegister(System.Action<object> callback, object state) Línea 248
</code>```

and then it starts repeating this calls until it overflows:

```<code>
    Microsoft.Extensions.Primitives.dll!Microsoft.Extensions.Primitives.CancellationChangeToken.RegisterChangeCallback(System.Action<object> callback, object state)
    Microsoft.Extensions.Primitives.dll!Microsoft.Extensions.Primitives.ChangeToken.ChangeTokenRegistration<System.Action>.RegisterChangeTokenCallback(Microsoft.Extensions.Primitives.IChangeToken token)
    Microsoft.Extensions.Primitives.dll!Microsoft.Extensions.Primitives.ChangeToken.ChangeTokenRegistration<System.__Canon>.OnChangeTokenFired()
    Microsoft.Extensions.Primitives.dll!Microsoft.Extensions.Primitives.ChangeToken.ChangeTokenRegistration<System.Action>.RegisterChangeTokenCallback.AnonymousMethod__7_0(object s)
    System.Private.CoreLib.dll!System.Threading.CancellationTokenSource.Invoke(System.Delegate d, object state, System.Threading.CancellationTokenSource source) Línea 902
    System.Private.CoreLib.dll!System.Threading.CancellationTokenSource.Register(System.Delegate callback, object stateForCallback, System.Threading.SynchronizationContext syncContext, System.Threading.ExecutionContext executionContext) Línea 610
    System.Private.CoreLib.dll!System.Threading.CancellationToken.Register(System.Delegate callback, object state, bool useSynchronizationContext, bool useExecutionContext) Línea 290
    System.Private.CoreLib.dll!System.Threading.CancellationToken.UnsafeRegister(System.Action<object> callback, object state) Línea 248
</code>```

Body:
I'm building an ASP .NET Core MVC app, and I started encountering a random StackOverflowException, it happens when the aplication is idle rather than when I perform an Http request, so I'm having a hard time finding where the problem might be. I have the stack trace, and I see a recursion that should be whats causing the call stack to overflow, but it is from a method from framework itself, so I can't find the underlying cause.

I tried simplifying my ViewModels using DTOs instead of model objects, and at first it looked like it was working, the app was working 8 hours without crashing with the StackOverflowException (normally it happened 10-15 minutes from when I started the app), but now it started happening again, here is my call stack:

>   System.Private.CoreLib.dll!System.ModuleHandle.ResolveMethod(System.Runtime.CompilerServices.QCallModule module, int methodToken, System.IntPtr* typeInstArgs, int typeInstCount, System.IntPtr* methodInstArgs, int methodInstCount)
    System.Private.CoreLib.dll!System.ModuleHandle.ResolveMethodHandleInternal(System.Reflection.RuntimeModule module, int methodToken, System.IntPtr[] typeInstantiationContext, int typeInstCount, System.IntPtr[] methodInstantiationContext, int methodInstCount) Línea 1405
    System.Private.CoreLib.dll!System.ModuleHandle.ResolveMethodHandle(int methodToken, System.RuntimeTypeHandle[] typeInstantiationContext, System.RuntimeTypeHandle[] methodInstantiationContext) Línea 1390
    System.Private.CoreLib.dll!System.RuntimeType.GetMethodBase(System.Reflection.RuntimeModule scope, int typeMetadataToken) Línea 1743
    System.Private.CoreLib.dll!System.Reflection.RuntimeCustomAttributeData.RuntimeCustomAttributeData(System.Reflection.RuntimeModule scope, System.Reflection.MetadataToken caCtorToken, System.Reflection.ConstArray blob) Línea 273
    System.Private.CoreLib.dll!System.Reflection.RuntimeCustomAttributeData.GetCustomAttributes(System.Reflection.RuntimeModule module, int tkTarget) Línea 213
    System.Private.CoreLib.dll!System.Reflection.RuntimeCustomAttributeData.GetCustomAttributesInternal(System.RuntimeType target) Línea 22
    System.Private.CoreLib.dll!System.Reflection.CustomAttributeData.GetCustomAttributes(System.Reflection.MemberInfo target) Línea 18
    Microsoft.Extensions.Logging.dll!Microsoft.Extensions.Logging.ProviderAliasUtilities.GetAlias(System.Type providerType)
    Microsoft.Extensions.Logging.dll!Microsoft.Extensions.Logging.LoggerRuleSelector.Select(Microsoft.Extensions.Logging.LoggerFilterOptions options, System.Type providerType, string category, out Microsoft.Extensions.Logging.LogLevel? minLevel, out System.Func<string, string, Microsoft.Extensions.Logging.LogLevel, bool> filter)
    Microsoft.Extensions.Logging.dll!Microsoft.Extensions.Logging.LoggerFactory.ApplyFilters(Microsoft.Extensions.Logging.LoggerInformation[] loggers)
    Microsoft.Extensions.Logging.dll!Microsoft.Extensions.Logging.LoggerFactory.RefreshFilters(Microsoft.Extensions.Logging.LoggerFilterOptions filterOptions)
    Microsoft.Extensions.Options.dll!Microsoft.Extensions.Options.OptionsMonitorExtensions.OnChange.AnonymousMethod__0(System.__Canon o, string _)
    Microsoft.Extensions.Options.dll!Microsoft.Extensions.Options.OptionsMonitor<System.__Canon>.ChangeTrackerDisposable.OnChange(System.__Canon options, string name)
    Microsoft.Extensions.Options.dll!Microsoft.Extensions.Options.OptionsMonitor<Microsoft.Extensions.Logging.LoggerFilterOptions>.InvokeChanged(string name)
    Microsoft.Extensions.Options.dll!Microsoft.Extensions.Options.OptionsMonitor<System.__Canon>..ctor.AnonymousMethod__6_2(string name)
    Microsoft.Extensions.Primitives.dll!Microsoft.Extensions.Primitives.ChangeToken.ChangeTokenRegistration<string>.OnChangeTokenFired()
    Microsoft.Extensions.Primitives.dll!Microsoft.Extensions.Primitives.ChangeToken.ChangeTokenRegistration<string>.RegisterChangeTokenCallback.AnonymousMethod__7_0(object s)
    System.Private.CoreLib.dll!System.Threading.CancellationTokenSource.Invoke(System.Delegate d, object state, System.Threading.CancellationTokenSource source) Línea 902
    System.Private.CoreLib.dll!System.Threading.CancellationTokenSource.CallbackNode.ExecuteCallback.AnonymousMethod__9_0(object s) Línea 1139
    System.Private.CoreLib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) Línea 183
    System.Private.CoreLib.dll!System.Threading.CancellationTokenSource.CallbackNode.ExecuteCallback() Línea 1141
    System.Private.CoreLib.dll!System.Threading.CancellationTokenSource.ExecuteCallbackHandlers(bool throwOnFirstException) Línea 722
    System.Private.CoreLib.dll!System.Threading.CancellationTokenSource.NotifyCancellation(bool throwOnFirstException) Línea 639
    System.Private.CoreLib.dll!System.Threading.CancellationTokenSource.Cancel() Línea 221
    Microsoft.Extensions.Configuration.dll!Microsoft.Extensions.Configuration.ConfigurationManager.RaiseChanged()
    Microsoft.Extensions.Configuration.dll!Microsoft.Extensions.Configuration.ConfigurationManager.AddSource.AnonymousMethod__1()
    Microsoft.Extensions.Primitives.dll!Microsoft.Extensions.Primitives.ChangeToken.OnChange.AnonymousMethod__0_0(System.Action callback)
    Microsoft.Extensions.Primitives.dll!Microsoft.Extensions.Primitives.ChangeToken.ChangeTokenRegistration<System.Action>.OnChangeTokenFired()
    Microsoft.Extensions.Primitives.dll!Microsoft.Extensions.Primitives.ChangeToken.ChangeTokenRegistration<System.Action>.RegisterChangeTokenCallback.AnonymousMethod__7_0(object s)
    System.Private.CoreLib.dll!System.Threading.CancellationTokenSource.Invoke(System.Delegate d, object state, System.Threading.CancellationTokenSource source) Línea 902
    System.Private.CoreLib.dll!System.Threading.CancellationTokenSource.CallbackNode.ExecuteCallback.AnonymousMethod__9_0(object s) Línea 1139
    System.Private.CoreLib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) Línea 183
    System.Private.CoreLib.dll!System.Threading.CancellationTokenSource.CallbackNode.ExecuteCallback() Línea 1141
    System.Private.CoreLib.dll!System.Threading.CancellationTokenSource.ExecuteCallbackHandlers(bool throwOnFirstException) Línea 722
    System.Private.CoreLib.dll!System.Threading.CancellationTokenSource.NotifyCancellation(bool throwOnFirstException) Línea 639
    System.Private.CoreLib.dll!System.Threading.CancellationTokenSource.Cancel() Línea 221
    Microsoft.Extensions.Configuration.dll!Microsoft.Extensions.Configuration.ConfigurationProvider.OnReload()
    Microsoft.Extensions.Configuration.FileExtensions.dll!Microsoft.Extensions.Configuration.FileConfigurationProvider.Load(bool reload)
    Microsoft.Extensions.Configuration.FileExtensions.dll!Microsoft.Extensions.Configuration.FileConfigurationProvider..ctor.AnonymousMethod__1_1()
    Microsoft.Extensions.Primitives.dll!Microsoft.Extensions.Primitives.ChangeToken.OnChange.AnonymousMethod__0_0(System.Action callback)
    Microsoft.Extensions.Primitives.dll!Microsoft.Extensions.Primitives.ChangeToken.ChangeTokenRegistration<System.Action>.OnChangeTokenFired()
    Microsoft.Extensions.Primitives.dll!Microsoft.Extensions.Primitives.ChangeToken.ChangeTokenRegistration<System.Action>.RegisterChangeTokenCallback.AnonymousMethod__7_0(object s)
    System.Private.CoreLib.dll!System.Threading.CancellationTokenSource.Invoke(System.Delegate d, object state, System.Threading.CancellationTokenSource source) Línea 902
    System.Private.CoreLib.dll!System.Threading.CancellationTokenSource.Register(System.Delegate callback, object stateForCallback, System.Threading.SynchronizationContext syncContext, System.Threading.ExecutionContext executionContext) Línea 610
    System.Private.CoreLib.dll!System.Threading.CancellationToken.Register(System.Delegate callback, object state, bool useSynchronizationContext, bool useExecutionContext) Línea 290
    System.Private.CoreLib.dll!System.Threading.CancellationToken.UnsafeRegister(System.Action<object> callback, object state) Línea 248

and then it starts repeating this calls until it overflows:

    Microsoft.Extensions.Primitives.dll!Microsoft.Extensions.Primitives.CancellationChangeToken.RegisterChangeCallback(System.Action<object> callback, object state)
    Microsoft.Extensions.Primitives.dll!Microsoft.Extensions.Primitives.ChangeToken.ChangeTokenRegistration<System.Action>.RegisterChangeTokenCallback(Microsoft.Extensions.Primitives.IChangeToken token)
    Microsoft.Extensions.Primitives.dll!Microsoft.Extensions.Primitives.ChangeToken.ChangeTokenRegistration<System.__Canon>.OnChangeTokenFired()
    Microsoft.Extensions.Primitives.dll!Microsoft.Extensions.Primitives.ChangeToken.ChangeTokenRegistration<System.Action>.RegisterChangeTokenCallback.AnonymousMethod__7_0(object s)
    System.Private.CoreLib.dll!System.Threading.CancellationTokenSource.Invoke(System.Delegate d, object state, System.Threading.CancellationTokenSource source) Línea 902
    System.Private.CoreLib.dll!System.Threading.CancellationTokenSource.Register(System.Delegate callback, object stateForCallback, System.Threading.SynchronizationContext syncContext, System.Threading.ExecutionContext executionContext) Línea 610
    System.Private.CoreLib.dll!System.Threading.CancellationToken.Register(System.Delegate callback, object state, bool useSynchronizationContext, bool useExecutionContext) Línea 290
    System.Private.CoreLib.dll!System.Threading.CancellationToken.UnsafeRegister(System.Action<object> callback, object state) Línea 248


问:
Update UIKit View From Hosted SwiftUI Selection
Have a UIKit Navigation Controller that is the root view controller in the hierarchy of the storyboards. One of the button items navigates to a UIHostedViewController that produces a SwiftUI View. That SwiftUI View is in and of itself a Tab View with tabs - and all of it works fine.

One of the crux of our development is displaying large data models for the user, and we could regain a bit of screen real estate if we utilize the Navigation bar of the UIKit Navigation.

A defining attribute of our individual views is the color coding of the header and footer, we have been able to change these colors easily as the SwiftUI Tab View just calls different views with different modifiers.

What we would like to do is have the selection of the SwiftUI Tab View set a shared property with the UIKit view that would then change the navigation bar color - however the way we setup a bound variable and reload the NavigationBar setup with a didSet on that variable does not seem to be working.

The code is almost exactly as follows, less a couple of views.

```<code>class SomeViewController: UIHostingController< MySwiftUITabView > {

var headerColor: Binding<UIColor> = .constant(UIColor.blue) {
    didSet {
        DispatchQueue.main.async(qos: .userInteractive) {
            self.setupUI()
        }
    }
}

var defaultColor: UIColor!
required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder, rootView: MySwiftUITabView(headerColor: headerColor))

    }

override func viewDidLoad() {
    super.viewDidLoad()
    defaultColor = self.navigationController?.navigationBar.backgroundColor
    setupUI()
}
override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    teardownUI()
}

func setupUI() {
    if let naviController = self.navigationController {
        let newNavBarAppearance = UINavigationBarAppearance()
        newNavBarAppearance.backgroundColor = headerColor.wrappedValue
        naviController.navigationBar.scrollEdgeAppearance = newNavBarAppearance
        naviController.navigationBar.compactAppearance = newNavBarAppearance
        naviController.navigationBar.standardAppearance = newNavBarAppearance
    }
}

func teardownUI() {
    if let naviController = self.navigationController {
        let oldNavBarAppearance = UINavigationBarAppearance()
        oldNavBarAppearance.backgroundColor = defaultColor
        naviController.navigationBar.scrollEdgeAppearance = oldNavBarAppearance
        naviController.navigationBar.compactAppearance = oldNavBarAppearance
        naviController.navigationBar.standardAppearance = oldNavBarAppearance
    }
}
}
</code>```

And the SwiftUI Tab View:

```<code>struct MySwiftUITabView: View {

@Binding var headerColor: UIColor

var body: some View {
    TabView(selection: $selectedTab){
        TestView()
            .tag(0)
            .onAppear {
                headerColor = .orange
            }
            .tabItem {
                Label("Test", image: "circle.fill")
            }
        TestView()
            .tag(1)
            .onAppear {
                headerColor = .red
            }
            .tabItem {
                Label("Test", image: "square.fill")
            }
    }
    .accentColor(.white)
}

}
</code>```

Would a callback be more appropriate for this? We wrapped the didSet function call in a DispatchGroup as a final attempt since it is updating the UI, but the was not effective still for what we are looking for.

In this example, the navigation bar remains the same color as the original set value (.blue) and never gets updated to the color set to the binding by the .onAppear of the swiftUI tab items.

Any help would be greatly appreciated as always!

Body:
Have a UIKit Navigation Controller that is the root view controller in the hierarchy of the storyboards. One of the button items navigates to a UIHostedViewController that produces a SwiftUI View. That SwiftUI View is in and of itself a Tab View with tabs - and all of it works fine.

One of the crux of our development is displaying large data models for the user, and we could regain a bit of screen real estate if we utilize the Navigation bar of the UIKit Navigation.

A defining attribute of our individual views is the color coding of the header and footer, we have been able to change these colors easily as the SwiftUI Tab View just calls different views with different modifiers.

What we would like to do is have the selection of the SwiftUI Tab View set a shared property with the UIKit view that would then change the navigation bar color - however the way we setup a bound variable and reload the NavigationBar setup with a didSet on that variable does not seem to be working.

The code is almost exactly as follows, less a couple of views.

class SomeViewController: UIHostingController< MySwiftUITabView > {

var headerColor: Binding<UIColor> = .constant(UIColor.blue) {
    didSet {
        DispatchQueue.main.async(qos: .userInteractive) {
            self.setupUI()
        }
    }
}

var defaultColor: UIColor!
required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder, rootView: MySwiftUITabView(headerColor: headerColor))

    }

override func viewDidLoad() {
    super.viewDidLoad()
    defaultColor = self.navigationController?.navigationBar.backgroundColor
    setupUI()
}
override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    teardownUI()
}

func setupUI() {
    if let naviController = self.navigationController {
        let newNavBarAppearance = UINavigationBarAppearance()
        newNavBarAppearance.backgroundColor = headerColor.wrappedValue
        naviController.navigationBar.scrollEdgeAppearance = newNavBarAppearance
        naviController.navigationBar.compactAppearance = newNavBarAppearance
        naviController.navigationBar.standardAppearance = newNavBarAppearance
    }
}

func teardownUI() {
    if let naviController = self.navigationController {
        let oldNavBarAppearance = UINavigationBarAppearance()
        oldNavBarAppearance.backgroundColor = defaultColor
        naviController.navigationBar.scrollEdgeAppearance = oldNavBarAppearance
        naviController.navigationBar.compactAppearance = oldNavBarAppearance
        naviController.navigationBar.standardAppearance = oldNavBarAppearance
    }
}
}

And the SwiftUI Tab View:

struct MySwiftUITabView: View {

@Binding var headerColor: UIColor

var body: some View {
    TabView(selection: $selectedTab){
        TestView()
            .tag(0)
            .onAppear {
                headerColor = .orange
            }
            .tabItem {
                Label("Test", image: "circle.fill")
            }
        TestView()
            .tag(1)
            .onAppear {
                headerColor = .red
            }
            .tabItem {
                Label("Test", image: "square.fill")
            }
    }
    .accentColor(.white)
}

}

Would a callback be more appropriate for this? We wrapped the didSet function call in a DispatchGroup as a final attempt since it is updating the UI, but the was not effective still for what we are looking for.

In this example, the navigation bar remains the same color as the original set value (.blue) and never gets updated to the color set to the binding by the .onAppear of the swiftUI tab items.

Any help would be greatly appreciated as always!


问:
Missing Symbol in Tensorflow Quantum import
I have gotten this missing symbol error now in both Anaconda on Mac and in Google Colab (where the screenshot is from).

NotFoundError: /usr/lib/python3/dist-packages/tensorflow_quantum/core/ops/_tfq_simulate_ops.so: cannot open shared object file: No such file or directory

screenshot of the error

This happens when I attempt to import tensorflow_quantum after installing tensorflow==2.4.1, the newest version of tensorflow-graphics, and of course, tensorflow-quantum into fresh versions of both an anaconda env with python 3.8 and a brand new colab notebook.

I #'ed out the import line for tensorflow_quantum and the same setup had no problem with tensorflow, keras, and tensorflow_graphics, so I believe the error is coming from that install, though I have had tensorflow_quantum working properly in colab many times.

Am I missing some well understood step in the install? I swear I am simply following this guide: https://www.tensorflow.org/quantum/install

Edit: My previous success seems to have been with tensorflow==2.7.0 and tensorflow_quantum==0.7.2, so I tried that as well and had the same result.

Edit: I started a new kernel and tried this again with success. Can someone please update the installation guide on the Tensorflow site to reflect these new versions?


问:
Nuxt useLazyAsyncData sharing results
I created a component in Vue 3. In this component I call an API that response with some data from server. The problem is when I istantiate two components in a page. In this case data results are shared.

This is case of use in my component:

```<code>const { pending, data } = useLazyAsyncData(() => props.apiCall.then(res => res));
</code>```

In my page:

```<code><InputSelect :label="'Category'" :apiCall="api.tag.getAll()" :iKey="'id'" :iText="'name'" v-model:value="model.category" />
<InputSelect :label="'Genre'" :apiCall="api.genre.getAll()" :iKey="'id'" :iText="'name'" v-model:value="model.genre" />
</code>```

What I obtain is that the first InputSelect is filled with same data of second. How can I disable this completely meaningless component sharing? Using key parameter of useLazyAsyncData is not a solution.

Title: Nuxt useLazyAsyncData sharing results

Body:
I created a component in Vue 3. In this component I call an API that response with some data from server. The problem is when I istantiate two components in a page. In this case data results are shared.

This is case of use in my component:

const { pending, data } = useLazyAsyncData(() => props.apiCall.then(res => res));

In my page:

<InputSelect :label="'Category'" :apiCall="api.tag.getAll()" :iKey="'id'" :iText="'name'" v-model:value="model.category" />
<InputSelect :label="'Genre'" :apiCall="api.genre.getAll()" :iKey="'id'" :iText="'name'" v-model:value="model.genre" />

What I obtain is that the first InputSelect is filled with same data of second. How can I disable this completely meaningless component sharing? Using key parameter of useLazyAsyncData is not a solution.


问:
Ctrl + P in Spyder but search in Project files
Is there a feature in Spyder to open any file from the opened project but not by browsing through directories but by typing it's name? There is a feature Ctrl+P which enable us to type the name of OPENED file but I'd like to open any file from project. It would be a big time saver.

Any suggestions?


问:
Oracle Apex Interactive Grid - Add new row not inserting
I have a page on my app that allows the user to create (insert) a new row on my table:

```<code>Employee   Manager    id    Status
john       ryan       1     Active
angela     ryan       2     Active
steve      jim        3     Inactive
</code>```

Id column acting as primary key.
My Interactive Grid is working ok for updates, the 'add row' button works (a new row is displayed and info can be added into it). But when clicking on save, this 'new row added' disappears, info doesn't get inserted into the table at all.
My query as follows:

```<code>select
--PK
id,
Manager,
Employee,
--Update only available when Status is active:
decode(Status,'Active', 'U',
                    'X') as Editable
from my_table

IG attributes:
Edit = enabled
Allowed Operations = update row, add row
Allowed Row Operations Column = Editable
Lost Update Type = row value
Add row if empty = Yes
</code>```

Anybody has any idea why?

Thank you all

Body:
I have a page on my app that allows the user to create (insert) a new row on my table:

Employee   Manager    id    Status
john       ryan       1     Active
angela     ryan       2     Active
steve      jim        3     Inactive

Id column acting as primary key.
My Interactive Grid is working ok for updates, the 'add row' button works (a new row is displayed and info can be added into it). But when clicking on save, this 'new row added' disappears, info doesn't get inserted into the table at all.
My query as follows:

select
--PK
id,
Manager,
Employee,
--Update only available when Status is active:
decode(Status,'Active', 'U',
                    'X') as Editable
from my_table

IG attributes:
Edit = enabled
Allowed Operations = update row, add row
Allowed Row Operations Column = Editable
Lost Update Type = row value
Add row if empty = Yes

Anybody has any idea why?

Thank you all


问:
Hyperledger fabric orderer fails after container restart
I have a Hyperledger Fabric network running on v1.4 & kubernetes version 1.16.15. Whenever the container is restarted it throws an error and keep crashing. Below are the logs:

```<code>panic: Error opening leveldb: no locks available

goroutine 1 [running]:
github.com/hyperledger/fabric/common/ledger/util/leveldbhelper.(*DB).Open(0xc0000ebbc0)
    /opt/gopath/src/github.com/hyperledger/fabric/common/ledger/util/leveldbhelper/leveldb_helper.go:80 +0x26b
github.com/hyperledger/fabric/common/ledger/util/leveldbhelper.NewProvider(0xc000206210, 0xc000206210)
    /opt/gopath/src/github.com/hyperledger/fabric/common/ledger/util/leveldbhelper/leveldb_provider.go:40 +0xda
github.com/hyperledger/fabric/common/ledger/blkstorage/fsblkstorage.NewProvider(0xc00036cb00, 0xc00036cb20, 0x1666020, 0x2039b68, 0x0, 0x0)
    /opt/gopath/src/github.com/hyperledger/fabric/common/ledger/blkstorage/fsblkstorage/fs_blockstore_provider.go:36 +0xc9
github.com/hyperledger/fabric/common/ledger/blockledger/file.New(0xc00061d410, 0x23, 0x1666020, 0x2039b68, 0xc000000180, 0x109c893)
    /opt/gopath/src/github.com/hyperledger/fabric/common/ledger/blockledger/file/factory.go:72 +0xf1
github.com/hyperledger/fabric/orderer/common/server.createLedgerFactory(0xc0000d6d80, 0x1666020, 0x2039b68, 0x0, 0x0, 0x0, 0x0)
    /opt/gopath/src/github.com/hyperledger/fabric/orderer/common/server/util.go:33 +0x1c9
github.com/hyperledger/fabric/orderer/common/server.Start(0x14cec62, 0x5, 0xc0000d6d80)
    /opt/gopath/src/github.com/hyperledger/fabric/orderer/common/server/main.go:109 +0x2f6
github.com/hyperledger/fabric/orderer/common/server.Main()
    /opt/gopath/src/github.com/hyperledger/fabric/orderer/common/server/main.go:91 +0x208
main.main()
    /opt/gopath/src/github.com/hyperledger/fabric/orderer/main.go:15 +0x20
</code>```

I have verified that the container receives termination signal but it exits right after that signal. Not sure if it being terminating gracefully

```<code>2023-01-09 04:47:14.066 UTC [orderer.common.server] handleSignals -> INFO 0d0 Received signal: 15 (terminated)
</code>```

I am not sure but can it be linked to kubernetes that it is terminating the pod and not giving an opportunity to gracefully shutdown the pod? The default terminationGracePeriodSeconds is set to 30 seconds.

Any suggestion would be helpful

Body:
I have a Hyperledger Fabric network running on v1.4 & kubernetes version 1.16.15. Whenever the container is restarted it throws an error and keep crashing. Below are the logs:

panic: Error opening leveldb: no locks available

goroutine 1 [running]:
github.com/hyperledger/fabric/common/ledger/util/leveldbhelper.(*DB).Open(0xc0000ebbc0)
    /opt/gopath/src/github.com/hyperledger/fabric/common/ledger/util/leveldbhelper/leveldb_helper.go:80 +0x26b
github.com/hyperledger/fabric/common/ledger/util/leveldbhelper.NewProvider(0xc000206210, 0xc000206210)
    /opt/gopath/src/github.com/hyperledger/fabric/common/ledger/util/leveldbhelper/leveldb_provider.go:40 +0xda
github.com/hyperledger/fabric/common/ledger/blkstorage/fsblkstorage.NewProvider(0xc00036cb00, 0xc00036cb20, 0x1666020, 0x2039b68, 0x0, 0x0)
    /opt/gopath/src/github.com/hyperledger/fabric/common/ledger/blkstorage/fsblkstorage/fs_blockstore_provider.go:36 +0xc9
github.com/hyperledger/fabric/common/ledger/blockledger/file.New(0xc00061d410, 0x23, 0x1666020, 0x2039b68, 0xc000000180, 0x109c893)
    /opt/gopath/src/github.com/hyperledger/fabric/common/ledger/blockledger/file/factory.go:72 +0xf1
github.com/hyperledger/fabric/orderer/common/server.createLedgerFactory(0xc0000d6d80, 0x1666020, 0x2039b68, 0x0, 0x0, 0x0, 0x0)
    /opt/gopath/src/github.com/hyperledger/fabric/orderer/common/server/util.go:33 +0x1c9
github.com/hyperledger/fabric/orderer/common/server.Start(0x14cec62, 0x5, 0xc0000d6d80)
    /opt/gopath/src/github.com/hyperledger/fabric/orderer/common/server/main.go:109 +0x2f6
github.com/hyperledger/fabric/orderer/common/server.Main()
    /opt/gopath/src/github.com/hyperledger/fabric/orderer/common/server/main.go:91 +0x208
main.main()
    /opt/gopath/src/github.com/hyperledger/fabric/orderer/main.go:15 +0x20

I have verified that the container receives termination signal but it exits right after that signal. Not sure if it being terminating gracefully

2023-01-09 04:47:14.066 UTC [orderer.common.server] handleSignals -> INFO 0d0 Received signal: 15 (terminated)

I am not sure but can it be linked to kubernetes that it is terminating the pod and not giving an opportunity to gracefully shutdown the pod? The default terminationGracePeriodSeconds is set to 30 seconds.

Any suggestion would be helpful


问:
How to trace all endpoints or methods with OpenTelemetry and manual configuring
I'm trying to use OpenTelemetry SDK to trace my java application. When I'm using auto configuration with opentelemetry-javaagent.jar I see a lot of methods traced. But when I'm using manual config I need to add spans for all methods I want to trace. How I can trace all methods and just filter some unnecessary ones with manual config?</p>


问:
Pyspark find min price within a date range in pyspark dataframe
I have a Dataframe which has following data(simulation).

Price
Date
InvoiceNumber
Product_Type

12.65
12/30/2021
INV_19984
AXN UN1234

18.78
1/23/2022
INV_200174
AXN UN1234

11.78
1/25/2022
INV_200173
AXN UN1234

11.1
3/2/2022
INV_9912
AXN UN1234

I am trying to find minimum price of the product in the last 30days, 60days and 90days without filtering the data. This data is huge and hence avoiding join operation so using a window function. But It returns null.

```<code>wi = Window.partitionBy("Product_Type").orderBy("Date").rowsBetween(30 ,Window.currentRow)
f1 = df.withColumn("minPrice30",F.min("price").over(wi))
</code>```

Expected output is :

minPrice60
minPrice30
Price
Date
InvoiceNumber
Product_Type

12.65
12.65
12.65
12/30/2021
INV_19984
AXN UN1234

12.65
12.65
18.78
1/23/2022
INV_200174
AXN UN1234

11.78
11.78
11.78
1/25/2022
INV_200173
AXN UN1234

11.1
11.1
11.1
3/2/2022
INV_9912
AXN UN1234

Is there any way we can achieve this within the date range?
Kindly Suggest

Body:
I have a Dataframe which has following data(simulation).

Price
Date
InvoiceNumber
Product_Type

12.65
12/30/2021
INV_19984
AXN UN1234

18.78
1/23/2022
INV_200174
AXN UN1234

11.78
1/25/2022
INV_200173
AXN UN1234

11.1
3/2/2022
INV_9912
AXN UN1234

I am trying to find minimum price of the product in the last 30days, 60days and 90days without filtering the data. This data is huge and hence avoiding join operation so using a window function. But It returns null.

wi = Window.partitionBy("Product_Type").orderBy("Date").rowsBetween(30 ,Window.currentRow)
f1 = df.withColumn("minPrice30",F.min("price").over(wi))

Expected output is :

minPrice60
minPrice30
Price
Date
InvoiceNumber
Product_Type

12.65
12.65
12.65
12/30/2021
INV_19984
AXN UN1234

12.65
12.65
18.78
1/23/2022
INV_200174
AXN UN1234

11.78
11.78
11.78
1/25/2022
INV_200173
AXN UN1234

11.1
11.1
11.1
3/2/2022
INV_9912
AXN UN1234

Is there any way we can achieve this within the date range?
Kindly Suggest


问:
Separating Redux Async Middleware and general API functions
I am currently using createAsyncThunk to create async middlewares for a React-Redux app I am working on in the following manner:

```<code>import axios from "axios";
import ApiUrls from "../ApiUrls";
import { createAsyncThunk } from "@reduxjs/toolkit";

class NftMiddleware{

//The middleware
  static fetchAllNfts = createAsyncThunk('nft/fetchAllNfts', async () => {
        const response = await axios.get(ApiUrls.getAllNftsUrl);
        return response.data;
    });

}

</code>```

Now if I want to also create a wrapper function for a fetch request without triggering any dispatch, should I add another static function to the NftMiddleware class like so:

```<code>
class NftMiddleware{

//The middleware
  static fetchAllNfts = createAsyncThunk('nft/fetchAllNfts', async () => {
        const response = await axios.get(ApiUrls.getAllNftsUrl);
        return response.data;
    });

//Not actually middleware, just a simple api call wrapper
    static postMetaData = async (data) => {
        const response = await axios.post(ApiUrls.postMetaData, data);
        return response.data;
    }
}

</code>```

Is this the right way of organizing my code that interacts with the backend? Should these be separate classes? For middleware and then for actual API calls? I can't help but feel I am doing things in an 'unclean' and unintuitive manner, as opposed to a more 'centralized' way.

Body:
I am currently using createAsyncThunk to create async middlewares for a React-Redux app I am working on in the following manner:

import axios from "axios";
import ApiUrls from "../ApiUrls";
import { createAsyncThunk } from "@reduxjs/toolkit";

class NftMiddleware{

//The middleware
  static fetchAllNfts = createAsyncThunk('nft/fetchAllNfts', async () => {
        const response = await axios.get(ApiUrls.getAllNftsUrl);
        return response.data;
    });

}

Now if I want to also create a wrapper function for a fetch request without triggering any dispatch, should I add another static function to the NftMiddleware class like so:

class NftMiddleware{

//The middleware
  static fetchAllNfts = createAsyncThunk('nft/fetchAllNfts', async () => {
        const response = await axios.get(ApiUrls.getAllNftsUrl);
        return response.data;
    });

//Not actually middleware, just a simple api call wrapper
    static postMetaData = async (data) => {
        const response = await axios.post(ApiUrls.postMetaData, data);
        return response.data;
    }
}

Is this the right way of organizing my code that interacts with the backend? Should these be separate classes? For middleware and then for actual API calls? I can't help but feel I am doing things in an 'unclean' and unintuitive manner, as opposed to a more 'centralized' way.


问:
Optimizing a path finding alg. from grid with rules
I'm trying to code a path finding algorithm, for this problem: You're given a grid with values, and your goal is to find the longest path from the highest point to the lowest point (least steep one).

I experimented with code I on here [https://stackoverflow.com/questions/68464767/find-a-path-from-grid-with-rules], but for large grids (e.g. 140x140). Since the code is checking every single possible route, it's taking really long to calculate it. Could I implement any stopping solution that would just not continue finding the path is the path isn't optimal ?

As i said earlier, i found code on here that works, but is just way too slow for me to use. Here's my code with the grid. The code works perfectly for smaller grids.

The code below itsn't full, because the grid is too large to be posted here. The full code can be found here - https://pastebin.com/q4nKS4rS

    def find_paths_recursive(grid, current_path=[(136,136)], solutions=[]):
    n = len(grid)
    dirs = [(-1,0), (1,0), (0,1), (0,-1)]

    last_cell = current_path[-1]

    for x,y in dirs:
        new_i = last_cell[0] + x
        new_j = last_cell[1] + y

        # Check if new cell is in grid
        if new_i<0 or new_i>=n or new_j<0 or new_j>=n:
            continue

        # Check if new cell has bigger value than last
        if grid[new_i][new_j] > grid[last_cell[0]][last_cell[1]]:
            continue

        # Check if new cell is already in path
        if (new_i, new_j) in current_path:
            continue

        # Add cell to current path
        current_path_copy = current_path.copy()
        current_path_copy.append((new_i, new_j))

        if new_i==0 and new_j ==0:
            solutions.append(current_path_copy)
        print(current_path_copy)
        # Create new current_path array for every direction
        find_paths_recursive(grid, current_path_copy, solutions)

    return solutions

def compute_cell_values(grid1, solutions):
    path_values = []

    for solution in solutions:
        solution_values = []
        for cell in solution:
            solution_values.append(grid1[cell[0]][cell[1]])
        path_values.append(solution_values)
    return path_values

grid1 = [...]

solutions = find_paths_recursive(grid1)
path_values = compute_cell_values(grid1, solutions)

print('Solutions:')
print(solutions)
print('Values:')
print(path_values)

```


问:
How to override inherited secrets in GitHub reusable actions?
I have workflows A and B that both call workflow C. There are many secrets that are set up in git repository. Workflow C uses 100 secrets. I need to pass 99 of them the same way from workflows A and B. But one of them are different. Can I make workflow C inherit all the secrets an override only one of them?
Something like:
A:

```<code>name: Reusable workflow
on:
  workflow_call:
    inputs:
    ...
env:
  SECRET_1: ${{ secrets.SECRET_1 }}
  SECRET_2: ${{ secrets.SECRET_2 }}
  ...
  SECRET_100: ${{ secrets.SECRET_100 }}
jobs:
   ...
</code>```

A:

```<code>name: Workflow A
on: ["workflow_dispatch"]

jobs:
  C:
    uses: ./.github/workflows/C.yaml
  secrets:
    - inherit
    - SECRET_100: ${{ secrets.SECRET_100_FOR_A }}
jobs:
   ...
</code>```

B:

```<code>name: Workflow B
on: ["workflow_dispatch"]

jobs:
  C:
    uses: ./.github/workflows/C.yaml
  secrets:
    - inherit
    - SECRET_100: ${{ secrets.SECRET_100_FOR_B }}
jobs:
   ...
</code>```

I've tried reading documentation and googling and also tried to pass every secret explicitly without inherit keyword - but it is not very scalable.

Body:
I have workflows A and B that both call workflow C. There are many secrets that are set up in git repository. Workflow C uses 100 secrets. I need to pass 99 of them the same way from workflows A and B. But one of them are different. Can I make workflow C inherit all the secrets an override only one of them?
Something like:
A:

name: Reusable workflow
on:
  workflow_call:
    inputs:
    ...
env:
  SECRET_1: ${{ secrets.SECRET_1 }}
  SECRET_2: ${{ secrets.SECRET_2 }}
  ...
  SECRET_100: ${{ secrets.SECRET_100 }}
jobs:
   ...

A:

name: Workflow A
on: ["workflow_dispatch"]

jobs:
  C:
    uses: ./.github/workflows/C.yaml
  secrets:
    - inherit
    - SECRET_100: ${{ secrets.SECRET_100_FOR_A }}
jobs:
   ...

B:

name: Workflow B
on: ["workflow_dispatch"]

jobs:
  C:
    uses: ./.github/workflows/C.yaml
  secrets:
    - inherit
    - SECRET_100: ${{ secrets.SECRET_100_FOR_B }}
jobs:
   ...

I've tried reading documentation and googling and also tried to pass every secret explicitly without inherit keyword - but it is not very scalable.


问:
PostgreSQL get associated record with limit and offset
I don't figure out how to group records and have X associated records by results
I have users with many books and want to have results of 3 books maximum by result</p>
```<code>user_id | book_ids |
--------+----------|
  1     | [1,2,3]  |
  1     | [4,5,6]  |
  1     | [7,8,9]  |
  2     | [1,2,3]  |
  2     | [4,5,6]  |
  3     | [1,2,3]  |
</code>```

Body:
I don't figure out how to group records and have X associated records by results
I have users with many books and want to have results of 3 books maximum by result

user_id | book_ids |
--------+----------|
  1     | [1,2,3]  |
  1     | [4,5,6]  |
  1     | [7,8,9]  |
  2     | [1,2,3]  |
  2     | [4,5,6]  |
  3     | [1,2,3]  |


问:
Select value from another table based on IF statement in SQL
In SQL Server DB I have two tables.

```<code>Customer | (CustomerAddressID1,CustomerAddressID2)
</code>```

They link to Address table

```<code>Address | (AddressID,Postcode)
</code>```

What is the best way to check the following condition in query?

If CustomerAddressID1 IS NOT NULL then get Postcode based on CustomerAddressID1 otherwise get Postcode based on CustomerAddressID2.

I was thinking along the lines of

Body:
In SQL Server DB I have two tables.

Customer | (CustomerAddressID1,CustomerAddressID2)

They link to Address table

Address | (AddressID,Postcode)

What is the best way to check the following condition in query?

If CustomerAddressID1 IS NOT NULL then get Postcode based on CustomerAddressID1 otherwise get Postcode based on CustomerAddressID2.

I was thinking along the lines of


问:
Trying to aggregate a sum over two gantt bars in tableau
As you can see, employee 6006 is aligned to two projects. I want to display the sum of commitment without having project ID in the view.

Like this:

When I add sum of commitment to the view it does not add the two values up it just gives two bars with a total of 50 for each rather than showing an overlapped sum of 100. Any ideas?


问:
"No overload matches this call" in Angular
I follow this tutorial : https://devdactic.com/sqlite-ionic-app-with-capacitor
But I got this error and I don't understand :

```<code>Error: src/app/services/database.service.ts:60:95 - error TS2769: No overload matches this call.
  Overload 1 of 3, '(observer?: Partial<Observer<Object>> | undefined): Subscription', gave the following error.
    Type '(jsonExport: JsonSQLite) => Promise<void>' has no properties in common with type 'Partial<Observer<Object>>'.
  Overload 2 of 3, '(next: (value: Object) => void): Subscription', gave the following error.
    Argument of type '(jsonExport: JsonSQLite) => Promise<void>' is not assignable to parameter of type '(value: Object) => void'.
      Types of parameters 'jsonExport' and 'value' are incompatible.
        The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?
          Type 'Object' is missing the following properties from type 'JsonSQLite': database, version, encrypted, mode, tables
  Overload 3 of 3, '(next?: ((value: Object) => void) | null | undefined, error?: ((error: any) => void) | null | undefined, complete?: (() => void) | null | undefined): Subscription', gave the following error.
    Argument of type '(jsonExport: JsonSQLite) => Promise<void>' is not assignable to parameter of type '(value: Object) => void'.
      Types of parameters 'jsonExport' and 'value' are incompatible.
        Type 'Object' is not assignable to type 'JsonSQLite'.
          The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?

60     this.http.get('https://devdactic.fra1.digitaloceanspaces.com/tutorial/db.json').subscribe(async (jsonExport: JsonSQLite): Promise<void> => {
</code>```

   this.http.get('https://devdactic.fra1.digitaloceanspaces.com/tutorial/db.json').subscribe(async (jsonExport: JsonSQLite) => Promise<void> => {

Body:
I follow this tutorial : https://devdactic.com/sqlite-ionic-app-with-capacitor
But I got this error and I don't understand :

Error: src/app/services/database.service.ts:60:95 - error TS2769: No overload matches this call.
  Overload 1 of 3, '(observer?: Partial<Observer<Object>> | undefined): Subscription', gave the following error.
    Type '(jsonExport: JsonSQLite) => Promise<void>' has no properties in common with type 'Partial<Observer<Object>>'.
  Overload 2 of 3, '(next: (value: Object) => void): Subscription', gave the following error.
    Argument of type '(jsonExport: JsonSQLite) => Promise<void>' is not assignable to parameter of type '(value: Object) => void'.
      Types of parameters 'jsonExport' and 'value' are incompatible.
        The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?
          Type 'Object' is missing the following properties from type 'JsonSQLite': database, version, encrypted, mode, tables
  Overload 3 of 3, '(next?: ((value: Object) => void) | null | undefined, error?: ((error: any) => void) | null | undefined, complete?: (() => void) | null | undefined): Subscription', gave the following error.
    Argument of type '(jsonExport: JsonSQLite) => Promise<void>' is not assignable to parameter of type '(value: Object) => void'.
      Types of parameters 'jsonExport' and 'value' are incompatible.
        Type 'Object' is not assignable to type 'JsonSQLite'.
          The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?

60     this.http.get('https://devdactic.fra1.digitaloceanspaces.com/tutorial/db.json').subscribe(async (jsonExport: JsonSQLite): Promise<void> => {

   this.http.get('https://devdactic.fra1.digitaloceanspaces.com/tutorial/db.json').subscribe(async (jsonExport: JsonSQLite) => Promise<void> => {


问:
vscode testing with pytest for dockerized Django project
i want to debug my tests in vscode for my Django project witch is set up in a docker container but the problem is it always says pytest discovery error,
sometimes it seems to not be able to import modules(for example models) inside the test file and after some configuration it seems to not find the test file itself. all the folders of my project have an init.py file so everything is treated as a package, by the way there is no problem importing modules in my Django project.
the odd thing is when I run pytest inside of my docker container it works fine but I want to debug the tests.
i am fairly new to this so any help would be welcomeenter image description here

I enabled pytest in the .vscode/settings.jsonenter image description here file as some other settings
I tried also creating a .env file with PYTHONPATH in it to my root folder cause every tutorial I found work with a virtual environment and not a docker container


问:
How can I disallow mypy `type: ignore` comments?
I would like for mypy to ignore or disallow any # type: ignore comments.

Is this possible, short of modifying source files to remove the comments?

Looking for the equivalent of flake8 --disable-noqa

Context

When we initially started type-checking our code we ignored a lot of type errors in order to bring it under coverage. Now we are ready to rachet up the quality of our typing and want to be able to locally disable all type ignore comments for a particular module (or the whole project).

Somewhat related to How to check if Mypy `# type: ignore` comments are still valid and required?

mypy command-line arguments docs

mypy configuration file

Edit:
Note, we already make use of the ignore-without-code rule


问:
Laravel multiple policies always authenticated?
I'm using Laravel 9 with the Laravel Spatie Permissions package. I have users and roles in my system. Users have roles, and depending on their permissions on their role they either can or can't create new users / new roles etc.

I've set up my UserPolicy and RolePolicy, and am passing my User model to each since it's the user that needs to be checked against what permissions they have, then in the controller of my choice, such as my RoleController I run:

/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    $this->authorize('viewAny', User::class);

    $roles = Role::with('permissions')->get();

    if (!$roles || count($roles) <= 0) {
        return response()->json([
            'message' => 'No roles found'
        ], 404);
    }

    return response()->json([
        'roles' => $roles
    ], 200);
}
```
<p>Strangely, if I edit my <code>RolePolicy</code>'s <code>viewAny</code> permission and return false, I'm still able to see the data? I shouldn't be. what am I missing?</p>
<p>Here's my <code>RolePolicy</code></p>
<pre class="lang-php prettyprint-override"><code><?php

namespace App\Policies\UserManagement;

use Spatie\Permission\Models\Role;
use App\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;

class RolePolicy
{
    use HandlesAuthorization;

    /**
     * Determine whether the user can view any models.
     *
     * @param  \App\Models\User  $user
     * @return \Illuminate\Auth\Access\Response|bool
     */
    public function viewAny(User $user)
    {
        // TODO: if I return false I still have access?
        if ($user->can('role_index')) {
            return true;
        }
    }

    /**
     * Determine whether the user can view the model.
     *
     * @param  \App\Models\User  $user
     * @return \Illuminate\Auth\Access\Response|bool
     */
    public function view(User $user)
    {
        if ($user->can('role_show')) {
            return true;
        }
    }

    /**
     * Determine whether the user can create models.
     *
     * @param  \App\Models\User  $user
     * @return \Illuminate\Auth\Access\Response|bool
     */
    public function create(User $user)
    {
        if ($user->can('role_store')) {
            return true;
        }
    }

    /**
     * Determine whether the user can update the model.
     *
     * @param  \App\Models\User  $user
     * @return \Illuminate\Auth\Access\Response|bool
     */
    public function update(User $user)
    {
        if ($user->can('role_update')) {
            return true;
        }
    }

    /**
     * Determine whether the user can delete the model.
     *
     * @param  \App\Models\User  $user
     * @return \Illuminate\Auth\Access\Response|bool
     */
    public function delete(User $user)
    {
        if ($user->can('role_destroy')) {
            return true;
        }
    }
}
</code>```

And my AuthServiceProvider:

<?php

namespace App\Providers;

use App\Models\User;
use Spatie\Permission\Models\Role;
use App\Policies\UserManagement\UserPolicy;
use App\Policies\UserManagement\RolePolicy;
use Illuminate\Support\Facades\Gate;
use Illuminate\Auth\Notifications\ResetPassword;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The model to policy mappings for the application.
     *
     * @var array<class-string, class-string>
     */
    protected $policies = [
        User::class => UserPolicy::class,
        User::class => RolePolicy::class,
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        ResetPassword::createUrlUsing(function ($user, string $token) {
            $frontendUrl = trim(rtrim(config('lespro.frontend_url'), '/'));
            return $frontendUrl . '/account/reset/?email=' . $user->email . '&token=' . $token;
        });

        // Implicitly grant "super_admin" role all permissions
        // This works in the app by using gate-related functions like auth()->user->can() and @can()
        Gate::before(function ($user, $ability) {
            return $user->hasRole('super_admin') ? true : null;
        });
    }
}
```

Body:
I'm using Laravel 9 with the Laravel Spatie Permissions package. I have users and roles in my system. Users have roles, and depending on their permissions on their role they either can or can't create new users / new roles etc.

I've set up my UserPolicy and RolePolicy, and am passing my User model to each since it's the user that needs to be checked against what permissions they have, then in the controller of my choice, such as my RoleController I run:

/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    $this->authorize('viewAny', User::class);

    $roles = Role::with('permissions')->get();

    if (!$roles || count($roles) <= 0) {
        return response()->json([
            'message' => 'No roles found'
        ], 404);
    }

    return response()->json([
        'roles' => $roles
    ], 200);
}

Strangely, if I edit my RolePolicy's viewAny permission and return false, I'm still able to see the data? I shouldn't be. what am I missing?

Here's my RolePolicy

<?php

namespace App\Policies\UserManagement;

use Spatie\Permission\Models\Role;
use App\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;

class RolePolicy
{
    use HandlesAuthorization;

    /**
     * Determine whether the user can view any models.
     *
     * @param  \App\Models\User  $user
     * @return \Illuminate\Auth\Access\Response|bool
     */
    public function viewAny(User $user)
    {
        // TODO: if I return false I still have access?
        if ($user->can('role_index')) {
            return true;
        }
    }

    /**
     * Determine whether the user can view the model.
     *
     * @param  \App\Models\User  $user
     * @return \Illuminate\Auth\Access\Response|bool
     */
    public function view(User $user)
    {
        if ($user->can('role_show')) {
            return true;
        }
    }

    /**
     * Determine whether the user can create models.
     *
     * @param  \App\Models\User  $user
     * @return \Illuminate\Auth\Access\Response|bool
     */
    public function create(User $user)
    {
        if ($user->can('role_store')) {
            return true;
        }
    }

    /**
     * Determine whether the user can update the model.
     *
     * @param  \App\Models\User  $user
     * @return \Illuminate\Auth\Access\Response|bool
     */
    public function update(User $user)
    {
        if ($user->can('role_update')) {
            return true;
        }
    }

    /**
     * Determine whether the user can delete the model.
     *
     * @param  \App\Models\User  $user
     * @return \Illuminate\Auth\Access\Response|bool
     */
    public function delete(User $user)
    {
        if ($user->can('role_destroy')) {
            return true;
        }
    }
}

And my AuthServiceProvider:

<?php

namespace App\Providers;

use App\Models\User;
use Spatie\Permission\Models\Role;
use App\Policies\UserManagement\UserPolicy;
use App\Policies\UserManagement\RolePolicy;
use Illuminate\Support\Facades\Gate;
use Illuminate\Auth\Notifications\ResetPassword;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The model to policy mappings for the application.
     *
     * @var array<class-string, class-string>
     */
    protected $policies = [
        User::class => UserPolicy::class,
        User::class => RolePolicy::class,
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        ResetPassword::createUrlUsing(function ($user, string $token) {
            $frontendUrl = trim(rtrim(config('lespro.frontend_url'), '/'));
            return $frontendUrl . '/account/reset/?email=' . $user->email . '&token=' . $token;
        });

        // Implicitly grant "super_admin" role all permissions
        // This works in the app by using gate-related functions like auth()->user->can() and @can()
        Gate::before(function ($user, $ability) {
            return $user->hasRole('super_admin') ? true : null;
        });
    }
}


问:
What is a "masker" when determining SHAP values in Python?
I am playing around with the SHAP Python module to get some insights in feature importance for my models. Since I'm applying various algorithms to my data, I was trying to define some generic lines of code at the end of my Jupyter notebook to generate the SHAP-values.

I had some trouble finding clear examples in the original documentation, but with some help from various sources I ended up with the code below. This works for xgboost XGBRegressor and also for sklearn RandomForestRegressor/LinearRegression/Lasso etc. So far so good!

```<code># Initiate the Explainer.
masker = shap.maskers.Independent(data=X_train, max_samples=100)
explainer = shap.Explainer(model=model, masker=masker)

# Generate the Explanations.
all_explanations = explainer(X_test)

# Extract the SHAP values.
shap_values = all_explanations.values
</code>```

What I figured out while working towards this solution, is that a LinearExplainer requires a "masker" parameter and a TreeExplainer doesn't (but it may be passed). Since I wanted generic code, I use the generic Explainer class including a "masker".

But I don't really understand what this "masker" is and/or does, and why it is required for one type of Explainer and not for the other? I cannot really find a clear conceptual explanation in the module documentation. On Medium there are numerous articles explaining about SHAP, but most of them use Tree-like models for which the "masker" is not required, and therefore it is not explained. Can anyone explain, or point to a good reference?

Edit

My question was marked as a duplicate of this question, but I'm looking for a little more in-depth explanation. Why is a "masker" required for one type of Explainer, but optional for the other? And what does it mean to provide the complete X_train as a "masker"? And what does the max_samples parameter do? I don't really find those answers in the other question.

I did find this useful resource, which got me a little further in understanding the background dataset (for which the "masker" is used).

I did find this useful resource, which explains that you should use X_train for the definition of the "masker" (as opposed to X_test).

Body:
I am playing around with the SHAP Python module to get some insights in feature importance for my models. Since I'm applying various algorithms to my data, I was trying to define some generic lines of code at the end of my Jupyter notebook to generate the SHAP-values.

I had some trouble finding clear examples in the original documentation, but with some help from various sources I ended up with the code below. This works for xgboost XGBRegressor and also for sklearn RandomForestRegressor/LinearRegression/Lasso etc. So far so good!

# Initiate the Explainer.
masker = shap.maskers.Independent(data=X_train, max_samples=100)
explainer = shap.Explainer(model=model, masker=masker)

# Generate the Explanations.
all_explanations = explainer(X_test)

# Extract the SHAP values.
shap_values = all_explanations.values

What I figured out while working towards this solution, is that a LinearExplainer requires a "masker" parameter and a TreeExplainer doesn't (but it may be passed). Since I wanted generic code, I use the generic Explainer class including a "masker".

But I don't really understand what this "masker" is and/or does, and why it is required for one type of Explainer and not for the other? I cannot really find a clear conceptual explanation in the module documentation. On Medium there are numerous articles explaining about SHAP, but most of them use Tree-like models for which the "masker" is not required, and therefore it is not explained. Can anyone explain, or point to a good reference?

Edit

My question was marked as a duplicate of this question, but I'm looking for a little more in-depth explanation. Why is a "masker" required for one type of Explainer, but optional for the other? And what does it mean to provide the complete X_train as a "masker"? And what does the max_samples parameter do? I don't really find those answers in the other question.

I did find this useful resource, which got me a little further in understanding the background dataset (for which the "masker" is used).

I did find this useful resource, which explains that you should use X_train for the definition of the "masker" (as opposed to X_test).


问:
Chi-square value from xarray polyfit
How can we derive the chi square values of the polynomial fit using xarray.Dataset.polyfit.
From what I can see in he documentation, it returns residuals and covariance matrix.
for example, I can calculate the 2nd order polynomial fit across dim1 of my dataarray

```<code>fit_param = ds.polyfit(dim='dim1', deg=2, cov=True)
</code>```

Title: Chi-square value from xarray polyfit

Body:
How can we derive the chi square values of the polynomial fit using xarray.Dataset.polyfit.
From what I can see in he documentation, it returns residuals and covariance matrix.
for example, I can calculate the 2nd order polynomial fit across dim1 of my dataarray

fit_param = ds.polyfit(dim='dim1', deg=2, cov=True)


问:
Pghero maximum query length in query stats
A couple of our longest running queries exceed 10,000 characters, but cannot be analysed through the pghero interface because they have been truncated to around 9980 characters.

I had a look through the code but couldn't see any limitations being imposed.

Is this limit derived from the postgresql track_activity_query_size value, perhaps?


问:
How to efficiently insert 100k+ rows into SQL database with Python
Using ODBC driver 18 for Windows, latest Python and pyodbc versions. SQL server is in Azure. Running the script from an Azure Function APP.

I have a script that executes the following steps:

Makes an API call, transforms the data as needed, saves each row with its column data as a list in a list (thereby making a list of lists).

Connects to a database, and inserts the list into its corresponding table (in the example below, 50k lists get inserted into the database at once).

As an example, one of the API calls returns 50k rows, with 46 columns each:

This is the function that inserts the data into the table:

And this is the function that returns the string on where to insert the data (this is not important but I put it as reference):

All this code works fine. However, it seems to me it could be better. Especially for some of the other APIs that return 100k or even more rows to be inserted.

What would be the proper way of going about this? Currently, inserting 100k rows takes about 4-5 minutes, for example.

I haven't tried anything else since I'm a bit of a beginner when it comes to working with databases in this way.


问:
modify the size of an image according to a circle so that the two images are superimposed by having the circle of each one on top of the other PYTHON
I have two input images: one is the template and the other is the image that the user will provide. They don't necessarily have the same size. Their only common point is a circle.

This circle I want the second image to adapt to have the same dimmension. So by zooming in or out and moving the circle so that the two images are superimposed with the circle which is well aligned.

I tried a lot of things to resize the circles to the same size and to align them but I didn't succeed in anything.

import cv2
import matplotlib.pyplot as plt
import numpy as np

# Charger les images
before_image = cv2.imread("before.jpg")
after_image = cv2.imread("center_after_2.jpg")
gray_before = cv2.cvtColor(before_image, cv2.COLOR_BGR2GRAY)
gray_after = cv2.cvtColor(after_image, cv2.COLOR_BGR2GRAY)

# Appliquer une réduction de bruit pour faciliter la détection de cercles
gray_before = cv2.medianBlur(gray_before, 5)
gray_after = cv2.medianBlur(gray_after, 5)

# Détecter les cercles dans les images
circles_before = cv2.HoughCircles(gray_before, cv2.HOUGH_GRADIENT, 1, 20, param1=150, param2=30, minRadius=0, maxRadius=0)
circles_after = cv2.HoughCircles(gray_after, cv2.HOUGH_GRADIENT, 1, 30, param1=150, param2=150, minRadius=0, maxRadius=0)

# Extraire les coordonnées x, y, et rayon du cercle dans les images
x1, y1, r1 = int(circles_before[0, 0, 0]), int(circles_before[0, 0, 1]), int(circles_before[0, 0, 2])
x2, y2, r2 = int(circles_after[0, 0, 0]), int(circles_after[0, 0, 1]), int(circles_after[0, 0, 2])

before_image = cv2.cvtColor(before_image, cv2.COLOR_BGR2RGB)
cv2.circle(before_image, (x1, y1), r1, (255,0,0), 2)
before_image = cv2.cvtColor(before_image, cv2.COLOR_BGR2RGB)
cv2.circle(after_image, (x2, y2), r2, (255,0,0), 2)

plt.imshow(before_image)
plt.show()

plt.imshow(after_image)
plt.show()
```

before_image and after_image

before_image

center_after_2

Body:
I have two input images: one is the template and the other is the image that the user will provide. They don't necessarily have the same size. Their only common point is a circle.

This circle I want the second image to adapt to have the same dimmension. So by zooming in or out and moving the circle so that the two images are superimposed with the circle which is well aligned.

I tried a lot of things to resize the circles to the same size and to align them but I didn't succeed in anything.

import cv2
import matplotlib.pyplot as plt
import numpy as np

# Charger les images
before_image = cv2.imread("before.jpg")
after_image = cv2.imread("center_after_2.jpg")
gray_before = cv2.cvtColor(before_image, cv2.COLOR_BGR2GRAY)
gray_after = cv2.cvtColor(after_image, cv2.COLOR_BGR2GRAY)

# Appliquer une réduction de bruit pour faciliter la détection de cercles
gray_before = cv2.medianBlur(gray_before, 5)
gray_after = cv2.medianBlur(gray_after, 5)

# Détecter les cercles dans les images
circles_before = cv2.HoughCircles(gray_before, cv2.HOUGH_GRADIENT, 1, 20, param1=150, param2=30, minRadius=0, maxRadius=0)
circles_after = cv2.HoughCircles(gray_after, cv2.HOUGH_GRADIENT, 1, 30, param1=150, param2=150, minRadius=0, maxRadius=0)

# Extraire les coordonnées x, y, et rayon du cercle dans les images
x1, y1, r1 = int(circles_before[0, 0, 0]), int(circles_before[0, 0, 1]), int(circles_before[0, 0, 2])
x2, y2, r2 = int(circles_after[0, 0, 0]), int(circles_after[0, 0, 1]), int(circles_after[0, 0, 2])

before_image = cv2.cvtColor(before_image, cv2.COLOR_BGR2RGB)
cv2.circle(before_image, (x1, y1), r1, (255,0,0), 2)
before_image = cv2.cvtColor(before_image, cv2.COLOR_BGR2RGB)
cv2.circle(after_image, (x2, y2), r2, (255,0,0), 2)

plt.imshow(before_image)
plt.show()

plt.imshow(after_image)
plt.show()

before_image and after_image

before_image

center_after_2


问:
“impellerc” can’t be opened because Apple cannot check it for malicious software
When I open visual code and execute flutter project it give me this error what can i do next any solution for this error.

enter image description here

I am trying to run the project.


问:
How to write a unit test for a class method with dependency injection?
I am learning Unit test in Symfony. I have a class that makes a client request

```<code>class Client
{
    public function __construct(
        private readonly string $url,
        private readonly HttpClientInterface $httpClient
    ) {
    }

    /**
     * @throws TransportExceptionInterface
     */
    public function makeRequest(string $filename): array
    {
        try {
            $response = $this->httpClient->request(
                Request::METHOD_GET,
                $this->url . "$filename.json"
            );

            return $this->processResponse($response);
        } catch (TransportException $e) {
            throw new TransportException($e->getMessage());
        }
    }
</code>```

I am trying to do the unit test for makeRequest method. So far I have tried this but I am not going anywhere. First I am not able to pass dependency. Second how to check if url is correct and returning valid output.

```<code>class ClientTest extends WebTestCase
{
    private $httpClient = null;

    protected function setUp(): void
    {
        self::bootKernel();
        $container = self::$kernel->getContainer();

        $this->httpClient = $container->get('http_client');
    }
    public function testIfRequestReturnsResult()
    {
        $controller = new Client();

    }
}
</code>```

Body:
I am learning Unit test in Symfony. I have a class that makes a client request

class Client
{
    public function __construct(
        private readonly string $url,
        private readonly HttpClientInterface $httpClient
    ) {
    }

    /**
     * @throws TransportExceptionInterface
     */
    public function makeRequest(string $filename): array
    {
        try {
            $response = $this->httpClient->request(
                Request::METHOD_GET,
                $this->url . "$filename.json"
            );

            return $this->processResponse($response);
        } catch (TransportException $e) {
            throw new TransportException($e->getMessage());
        }
    }

I am trying to do the unit test for makeRequest method. So far I have tried this but I am not going anywhere. First I am not able to pass dependency. Second how to check if url is correct and returning valid output.

class ClientTest extends WebTestCase
{
    private $httpClient = null;

    protected function setUp(): void
    {
        self::bootKernel();
        $container = self::$kernel->getContainer();

        $this->httpClient = $container->get('http_client');
    }
    public function testIfRequestReturnsResult()
    {
        $controller = new Client();

    }
}


问:
Crystal Reports 2020 - How to Supress a Group Header if Every item in Detials is Supressed
In Crystal Report 2020, I have a formula for supressing details based on certain criteria. I need to supress the Group Header if every item in the details is supressed based on that criteria. How do I do that?

The formula for supressing the detials is:

```<code>(ToText({MIMORD.lineNbr})<> "1.00"

AND

ToText(previous({MIMORD.compQty_form}))= "0.00"

AND

{MIMORD.wcId}<>previous({MIMORD.wcId})

)

OR

({MIMORD.compQty_form}={MIMORD.MIMOH.ordQty_form})

OR

({EXTRAS.val5} <> ""

AND {EXTRAS.val5} <> {MIMORD.wcId})
</code>```

Screenshot of my report is below. I'd also like to supress Group Header #1 if Group header #2 is supressed for all records.

I know there is a method to count the rows supressed using a summary formula but bevause I have the previous() function in my formula, I am getting an error that I can not use a summary formula.

Crystal Report Screenshot

Body:
In Crystal Report 2020, I have a formula for supressing details based on certain criteria. I need to supress the Group Header if every item in the details is supressed based on that criteria. How do I do that?

The formula for supressing the detials is:

(ToText({MIMORD.lineNbr})<> "1.00"

AND

ToText(previous({MIMORD.compQty_form}))= "0.00"

AND

{MIMORD.wcId}<>previous({MIMORD.wcId})

)

OR

({MIMORD.compQty_form}={MIMORD.MIMOH.ordQty_form})

OR

({EXTRAS.val5} <> ""

AND {EXTRAS.val5} <> {MIMORD.wcId})

Screenshot of my report is below. I'd also like to supress Group Header #1 if Group header #2 is supressed for all records.

I know there is a method to count the rows supressed using a summary formula but bevause I have the previous() function in my formula, I am getting an error that I can not use a summary formula.

Crystal Report Screenshot