问:
Assigning CanvasKit / Skia in Flutter Web causes my Googlemap's plugin to request 2 fingered use on mobile
I have mad jank when scrolling a ListView. Its scrolling a column of Text widgets interspersed with ElevatedButton Widgets, each time the user Scrolls and an ElevatedButton scrolls into view there's a bunch of jank, horrible.

On Flutter web desktop this doesn't happen, so I forced Flutter web mobile to use Skia rendering, by inserting this into my index.html file:

```<code><script>
  // This sets the Flutter web renderer in auto detect mode.
  // See https://stackoverflow.com/a/64583462/6509751.
  window.flutterWebRenderer = 'canvaskit';
</script>
</code>```

But this seemingly causes the Googlemap's plugin to believe that it is being used on a desktop not mobile, and it requests 2 fingered use.

This is not the paradigm for Googlemaps on mobile and I vaguely believe jank is better.

I would like it to work well on both desktop & mobile, is there a way to correct the google map plugin to use the mobile / desktop paradigms?

Body:
I have mad jank when scrolling a ListView. Its scrolling a column of Text widgets interspersed with ElevatedButton Widgets, each time the user Scrolls and an ElevatedButton scrolls into view there's a bunch of jank, horrible.

On Flutter web desktop this doesn't happen, so I forced Flutter web mobile to use Skia rendering, by inserting this into my index.html file:

But this seemingly causes the Googlemap's plugin to believe that it is being used on a desktop not mobile, and it requests 2 fingered use.

This is not the paradigm for Googlemaps on mobile and I vaguely believe jank is better.

I would like it to work well on both desktop & mobile, is there a way to correct the google map plugin to use the mobile / desktop paradigms?


来源: stackexchange

问:
How to shift Tooltip in Pygal?
I am creating an interactive World Map in Python with help of Pygal. My plan is to use the tooltip to display which country you are hovering over, and then upon clicking the country, it takes you to a seperate HTML with information on it. The problem is, sometimes the Tooltips themselves block the countries I am trying to access. For example, if I try and click on a small country like Switzerland, it's tooltip itself is so big that I can't click the country and redirect to the info page.

I have searched over and under for syntaxes that use Tooltips but can find none. I just want to be able to display which country the mouse is currently hovering over, and then redirect upon click. Possible solutions I think of include:

Adding a Hyperlink to the tooltip itself, like what is possible in the charts of pygal but for some reason not possible in the maps

Permanently setting the Tooltip's position to below the cursor

Completely disable Tooltips and just display the name of the country on the map like a normal physical world map

Below is the code that I have until now, but as a Prototype, with a model using only Continents instead of Countries. I do not yet have the HTML sites for all the countries because of this infuriating problem !

```<code>import pygal
from pygal_maps_world.maps import SupranationalWorld as SW
from pygal.style import Style

myworldmap = pygal.maps.world.SupranationalWorld
myworldmap.title = 'The Continents of the World'

my_style = Style(colors=('#FF0000', '#FFFF00', '#00008B', '#FFA500', '#00FFFF', '#A020F0', '#FFFFFF'))
myworldmap = SW(style= my_style)

myworldmap.tooltip_font_size = 15 #fontsize control
myworldmap.tooltip_border_radius = 5 #bordersize control

myworldmap.add('Africa', [{'value':('africa'),
                           'xlink': 'https://en.wikipedia.org/wiki/Africa',
                           'formatter': lambda x:'Africa'
                           }])

myworldmap.add('North America', [{'value':('north_america'),
                           'xlink': 'https://en.wikipedia.org/wiki/North_America',
                           'formatter': lambda x:'North America'
                           }])

myworldmap.add('South America', [{'value':('south_america'),
                           'xlink': 'https://en.wikipedia.org/wiki/South_America',
                           'formatter': lambda x:'South America'
                           }])

myworldmap.add('Asia', [{'value':('asia'),
                           'xlink': 'https://en.wikipedia.org/wiki/Asia',
                           'formatter': lambda x:'Asia'
                           }])

myworldmap.add('Europe', [{'value':('europe'),
                           'xlink': 'https://en.wikipedia.org/wiki/Europe',
                           'formatter': lambda x:'Europe'
                           }])

myworldmap.add('Oceania', [{'value':('oceania'),
                           'xlink': 'https://en.wikipedia.org/wiki/Oceania',
                           'formatter': lambda x:'Oceania'
                           }])

myworldmap.add('Antartica', [{'value':('antartica'),
                           'xlink': 'https://en.wikipedia.org/wiki/Antarctica',
                           'formatter': lambda x:'Antartica'
                           }])

myworldmap.render_to_file('worldmappic.svg')
print("Sucess")

</code>```

ContentLicense: CC BY-SA 4.0

Title: How to shift Tooltip in Pygal?

Body:
I am creating an interactive World Map in Python with help of Pygal. My plan is to use the tooltip to display which country you are hovering over, and then upon clicking the country, it takes you to a seperate HTML with information on it. The problem is, sometimes the Tooltips themselves block the countries I am trying to access. For example, if I try and click on a small country like Switzerland, it's tooltip itself is so big that I can't click the country and redirect to the info page.

I have searched over and under for syntaxes that use Tooltips but can find none. I just want to be able to display which country the mouse is currently hovering over, and then redirect upon click. Possible solutions I think of include:

Adding a Hyperlink to the tooltip itself, like what is possible in the charts of pygal but for some reason not possible in the maps

Permanently setting the Tooltip's position to below the cursor

Completely disable Tooltips and just display the name of the country on the map like a normal physical world map

Below is the code that I have until now, but as a Prototype, with a model using only Continents instead of Countries. I do not yet have the HTML sites for all the countries because of this infuriating problem !

import pygal
from pygal_maps_world.maps import SupranationalWorld as SW
from pygal.style import Style

myworldmap = pygal.maps.world.SupranationalWorld
myworldmap.title = 'The Continents of the World'

my_style = Style(colors=('#FF0000', '#FFFF00', '#00008B', '#FFA500', '#00FFFF', '#A020F0', '#FFFFFF'))
myworldmap = SW(style= my_style)

myworldmap.tooltip_font_size = 15 #fontsize control
myworldmap.tooltip_border_radius = 5 #bordersize control

myworldmap.add('Africa', [{'value':('africa'),
                           'xlink': 'https://en.wikipedia.org/wiki/Africa',
                           'formatter': lambda x:'Africa'
                           }])

myworldmap.add('North America', [{'value':('north_america'),
                           'xlink': 'https://en.wikipedia.org/wiki/North_America',
                           'formatter': lambda x:'North America'
                           }])

myworldmap.add('South America', [{'value':('south_america'),
                           'xlink': 'https://en.wikipedia.org/wiki/South_America',
                           'formatter': lambda x:'South America'
                           }])

myworldmap.add('Asia', [{'value':('asia'),
                           'xlink': 'https://en.wikipedia.org/wiki/Asia',
                           'formatter': lambda x:'Asia'
                           }])

myworldmap.add('Europe', [{'value':('europe'),
                           'xlink': 'https://en.wikipedia.org/wiki/Europe',
                           'formatter': lambda x:'Europe'
                           }])

myworldmap.add('Oceania', [{'value':('oceania'),
                           'xlink': 'https://en.wikipedia.org/wiki/Oceania',
                           'formatter': lambda x:'Oceania'
                           }])

myworldmap.add('Antartica', [{'value':('antartica'),
                           'xlink': 'https://en.wikipedia.org/wiki/Antarctica',
                           'formatter': lambda x:'Antartica'
                           }])

myworldmap.render_to_file('worldmappic.svg')
print("Sucess")


问:
Conda deleted itself during package installation error: how to restore it?
During package installation on my Windows, there was an error, during which conda (most probably) deleted itself. Now, conda command is not present on my Windows.

The main error is:

```<code>ERROR conda.core.link:_execute(733):
An error occurred while installing package 'defaults::conda-22.11.0-py39haa95532_1'
</code>```

Question. How can I restore conda command without (deleting and) reinstalling all Anaconda?
I do not want t lose all installed packages, environments, etc. and reinstall everything. Is there a solution to this?

Details:

The result of OCR tool (I could not just copy-paste):

```<code>
C:\WINDOWS\system32> conda install -c conda-forge textblob

Collecting package metadata (current_repodata.json): done
Solving environment: done

## Package Plan ##

environment location: C:\Users\user\anaconda3

added / updated specs:
- textblob

The following packages will be downloaded:
package                     |   build
----------------------------|---------------
conda-22.11.0               |   py39haa9SS32_1  932 KB
openssl-l.l.ls              |   hcfcfb64_1      5.1 MB  conda-forge
ruamel.yaml-0.16.12         |   py39h2bbfflb_3  173 KB
ruamel.yaml.clib-0.2.7      |   py39ha55989b_0  111 KB  conda-forge
------------------------------------------------------
                                        Total:  6.3 MB

The following NEW packages will be INSTALLED:

ruamel.yaml       pkgs/main/win-64::ruamel.yaml-0.16.12-py39h2bbfflb_3 None
ruamel.yaml.clib  conda-forge/win-64::ruamel.yaml.clib-0.2.7-py39ha55989b_0 None
textblob          conda-forge/noarch::textblob-0.15.3-py_0 None

The following packages will be UPDATED:

conda   conda-forge::conda-22.9.0-py39hcbf530- --> pkgs/main::conda-22.11.0-py39haa95532_l None
openssl l.l.ls-hcfcfb64_0 --> 1.1.ls-hcfcfb64_l None

Proceed ([y]/n)? y

Downloading and Extracting Packages
openssl-l.l.ls       |  5.1 MB  |
ruamel.yaml-0.16.12  |  173 KB
conda-22.11.0        |  932 KB
ruamel.yaml.clib-0.2 |  111 KB  |

Preparing transaction:  done
Verifying transaction:  done
Executing transaction:  done

ERROR conda.core.link:_execute(733): An error occurred while installing package 'defaults::conda-22.11.0-py39haa95532_1'.
Rolling back transaction: done

CondaError: Cannot link a source that does not exist.
C:\Users\user\anaconda3\.condatmp\0d55d647-3842-4S31-a301-4bedl75b9998
Running 'conda clean --packages' may resolve your problem.
()
[Errno 2] No such file or directory: ’C:\\Users\\user\\anaconda3\\conda-meta\\openssl-l.l.ls-hcfcfb64_0.json’
[Errno 2] No such file or directory: ’C:\\Users\\user\\anaconda3\\conda-meta\\conda-22.9.0-py39hcbf5309_2.json’

The batch file cannot be found.
The batch file cannot be found.

</code>```

Body:
During package installation on my Windows, there was an error, during which conda (most probably) deleted itself. Now, conda command is not present on my Windows.

The main error is:

ERROR conda.core.link:_execute(733):
An error occurred while installing package 'defaults::conda-22.11.0-py39haa95532_1'

Question. How can I restore conda command without (deleting and) reinstalling all Anaconda?
I do not want t lose all installed packages, environments, etc. and reinstall everything. Is there a solution to this?

Details:

The result of OCR tool (I could not just copy-paste):

C:\WINDOWS\system32> conda install -c conda-forge textblob

Collecting package metadata (current_repodata.json): done
Solving environment: done

## Package Plan ##

environment location: C:\Users\user\anaconda3

added / updated specs:
- textblob

The following packages will be downloaded:
package                     |   build
----------------------------|---------------
conda-22.11.0               |   py39haa9SS32_1  932 KB
openssl-l.l.ls              |   hcfcfb64_1      5.1 MB  conda-forge
ruamel.yaml-0.16.12         |   py39h2bbfflb_3  173 KB
ruamel.yaml.clib-0.2.7      |   py39ha55989b_0  111 KB  conda-forge
------------------------------------------------------
                                        Total:  6.3 MB

The following NEW packages will be INSTALLED:

ruamel.yaml       pkgs/main/win-64::ruamel.yaml-0.16.12-py39h2bbfflb_3 None
ruamel.yaml.clib  conda-forge/win-64::ruamel.yaml.clib-0.2.7-py39ha55989b_0 None
textblob          conda-forge/noarch::textblob-0.15.3-py_0 None

The following packages will be UPDATED:

conda   conda-forge::conda-22.9.0-py39hcbf530- --> pkgs/main::conda-22.11.0-py39haa95532_l None
openssl l.l.ls-hcfcfb64_0 --> 1.1.ls-hcfcfb64_l None

Proceed ([y]/n)? y

Downloading and Extracting Packages
openssl-l.l.ls       |  5.1 MB  |
ruamel.yaml-0.16.12  |  173 KB
conda-22.11.0        |  932 KB
ruamel.yaml.clib-0.2 |  111 KB  |

Preparing transaction:  done
Verifying transaction:  done
Executing transaction:  done

ERROR conda.core.link:_execute(733): An error occurred while installing package 'defaults::conda-22.11.0-py39haa95532_1'.
Rolling back transaction: done

CondaError: Cannot link a source that does not exist.
C:\Users\user\anaconda3\.condatmp\0d55d647-3842-4S31-a301-4bedl75b9998
Running 'conda clean --packages' may resolve your problem.
()
[Errno 2] No such file or directory: ’C:\\Users\\user\\anaconda3\\conda-meta\\openssl-l.l.ls-hcfcfb64_0.json’
[Errno 2] No such file or directory: ’C:\\Users\\user\\anaconda3\\conda-meta\\conda-22.9.0-py39hcbf5309_2.json’

The batch file cannot be found.
The batch file cannot be found.


问:
How do I extend a jest preset?
I am using expo so it provides a jest-expo preset.  What I want to do is add i18n-js to the transformIgnorePatterns since it seems to have an issue with Jest

```<code>  "jest": {
    "preset": "jest-expo",
    "transformIgnorePatterns": [
      "/node_modules/(?!i18n-js)(.*)"
    ]
  },
</code>```

So I took a variant of Jest gives an error: "SyntaxError: Unexpected token export" to implement the above but now I lose the existing patterns from the preset.  Is there a way of just adding another pattern to the preset?

Title: How do I extend a jest preset?

Body:
I am using expo so it provides a jest-expo preset.  What I want to do is add i18n-js to the transformIgnorePatterns since it seems to have an issue with Jest

  "jest": {
    "preset": "jest-expo",
    "transformIgnorePatterns": [
      "/node_modules/(?!i18n-js)(.*)"
    ]
  },

So I took a variant of Jest gives an error: "SyntaxError: Unexpected token export" to implement the above but now I lose the existing patterns from the preset.  Is there a way of just adding another pattern to the preset?


问:
SwiftUI Link to open Bundle files in browser
You can get the browser to open a URL with one line of code...

```<code>Link("Info", destination: URL(string: "https://my.web.address/info.pdf")!)
</code>```

You can compile and build this....

```<code>Link("Info", destination: Bundle.main.url(forResource: "info", withExtension: "pdf")!)
</code>```

No errors or crashes, but it does nothing. The Bundle.main.url() reply makes sense within the application, but does not work in the browser, which is not in the application. This was a security feature to stop people pulling data from your application, according to an answer from about 10 years back.

I have written a WKWebView page within my application to display the file. This works, but it took a lot more than one line. I would have actually preferred my original solution, if there had been some way for me to mark certain files as suitable for public release. As well as the manual, I have a PDF test chart image, and a table of CSV data that I would like to make public like this. I could use a button in the app to open them in the browser, and the user could then save a copy when and where they wanted. The user gets to re-use their browser skills, and I write one line of code per file. Win-win, right?

Can we open a Bundled file in the browser using a Link using some trick I haven't found yet? Is there a good reason why we must not do this?

Apologies if you have read (and possibly deleted) a question like this earlier today. I wrote this question, and I thought I had submitted it, but I can't find it now. So here it is again.

FWIW, here's my WKWebView page code...

```<code>import SwiftUI
import WebKit

struct WebView: UIViewRepresentable {
    typealias UIViewType = WKWebView

    var webView: WKWebView

    init() {
        webView = WKWebView(frame: .zero)
        webView.load(URLRequest(url: Bundle.main.url(forResource: "ByEye", withExtension: "pdf")!))
    }

    // Needed to make view UIViewRepresentable
    func makeUIView(context: Context) -> WKWebView { webView }
    func updateUIView(_ uiView: WKWebView, context: Context) { }
}

struct ManualView: View {

    var webView = WebView()

    var body: some View {
        webView
    }
}

struct ManualView_Previews: PreviewProvider {
    static var previews: some View {
        ManualView()
    }
}
</code>```

I found a partial solution. You can add text or images to the pasteboard, and then paste the data into an e-mail or other message. This does not work for a general file type, but it was enough to get me where I wanted.

See questions/74784691/swiftui-sharing-application-data-using-pasteboard

Body:
You can get the browser to open a URL with one line of code...

Link("Info", destination: URL(string: "https://my.web.address/info.pdf")!)

You can compile and build this....

Link("Info", destination: Bundle.main.url(forResource: "info", withExtension: "pdf")!)

No errors or crashes, but it does nothing. The Bundle.main.url() reply makes sense within the application, but does not work in the browser, which is not in the application. This was a security feature to stop people pulling data from your application, according to an answer from about 10 years back.

I have written a WKWebView page within my application to display the file. This works, but it took a lot more than one line. I would have actually preferred my original solution, if there had been some way for me to mark certain files as suitable for public release. As well as the manual, I have a PDF test chart image, and a table of CSV data that I would like to make public like this. I could use a button in the app to open them in the browser, and the user could then save a copy when and where they wanted. The user gets to re-use their browser skills, and I write one line of code per file. Win-win, right?

Can we open a Bundled file in the browser using a Link using some trick I haven't found yet? Is there a good reason why we must not do this?

Apologies if you have read (and possibly deleted) a question like this earlier today. I wrote this question, and I thought I had submitted it, but I can't find it now. So here it is again.

FWIW, here's my WKWebView page code...

import SwiftUI
import WebKit

struct WebView: UIViewRepresentable {
    typealias UIViewType = WKWebView

    var webView: WKWebView

    init() {
        webView = WKWebView(frame: .zero)
        webView.load(URLRequest(url: Bundle.main.url(forResource: "ByEye", withExtension: "pdf")!))
    }

    // Needed to make view UIViewRepresentable
    func makeUIView(context: Context) -> WKWebView { webView }
    func updateUIView(_ uiView: WKWebView, context: Context) { }
}

struct ManualView: View {

    var webView = WebView()

    var body: some View {
        webView
    }
}

struct ManualView_Previews: PreviewProvider {
    static var previews: some View {
        ManualView()
    }
}

I found a partial solution. You can add text or images to the pasteboard, and then paste the data into an e-mail or other message. This does not work for a general file type, but it was enough to get me where I wanted.

See questions/74784691/swiftui-sharing-application-data-using-pasteboard


问:
How to superimpose a barchart on a multiplot in Python
I have a code that plots two charts side by side. I want to additionally plot a bar chart on one of the two plots, with another quantity. My code indicates the hashed lines which would additionally plot a bar chart. But I want to plot this bar chart on a twin axis (its y label and limits on the right of the plot). Currently, the twinx() command does not work on a 1 by 2 plot and gives an error. My code is below</p>
```<code>def result_variability_onerow(variable1,variable2, yr):
    scenarios_PSN = {'Low Snow': 3, 'Medium Snow': 15, 'High Snow': 46}
    scenarios_TSN = {'Low Snow': 46, 'Medium Snow': 25, 'High Snow': 3}
    date_form = DateFormatter("%m-%y")

    plt.close()
    fig, ax = plt.subplots(1 , 2,  figsize = [15,5])
    # ax2 = ax.twinx()
    # ax2.set_ylim(4, 20)
    for key, value in scenarios_PSN.items():
        p = snow_vary[str(yr) + '_' + str(value)][150:250]
        ax[0].plot(p[variable1], label= str(key))
        ax[0].set_ylabel(str(variable1))
        ax[0].xaxis.set_major_formatter(date_form)
        ax[0].grid()
        ax[0].legend()

    for key, value in scenarios_TSN.items():
        t = temp_vary[str(yr) + '_' + str(value)][150:250]
        ax[1].plot(t[variable1], label= str(key))
        ax[1].xaxis.set_major_formatter(date_form)
        ax[1].grid()

    # ax[1].bar(t.index, t[variable2], label= "Precipitation")
    ax[0].set_title(variable1 + "Phase Change")
    ax[1].set_title(variable1 + "Temperature Change")
    ax[0].set_ylim(0,180)
    ax[1].set_ylim(0,180)
    ax[0].set_ylabel("Streamflow (mm)")
    plt.savefig('behaviour.pdf', format = 'pdf', bbox_inches = 'tight')

    print(str(variable1) + ' for the year ' + str(yr))

result_variability_onerow('streamflow','precip', 2005)
</code>```

Body:
I have a code that plots two charts side by side. I want to additionally plot a bar chart on one of the two plots, with another quantity. My code indicates the hashed lines which would additionally plot a bar chart. But I want to plot this bar chart on a twin axis (its y label and limits on the right of the plot). Currently, the twinx() command does not work on a 1 by 2 plot and gives an error. My code is below

def result_variability_onerow(variable1,variable2, yr):
    scenarios_PSN = {'Low Snow': 3, 'Medium Snow': 15, 'High Snow': 46}
    scenarios_TSN = {'Low Snow': 46, 'Medium Snow': 25, 'High Snow': 3}
    date_form = DateFormatter("%m-%y")

    plt.close()
    fig, ax = plt.subplots(1 , 2,  figsize = [15,5])
    # ax2 = ax.twinx()
    # ax2.set_ylim(4, 20)
    for key, value in scenarios_PSN.items():
        p = snow_vary[str(yr) + '_' + str(value)][150:250]
        ax[0].plot(p[variable1], label= str(key))
        ax[0].set_ylabel(str(variable1))
        ax[0].xaxis.set_major_formatter(date_form)
        ax[0].grid()
        ax[0].legend()

    for key, value in scenarios_TSN.items():
        t = temp_vary[str(yr) + '_' + str(value)][150:250]
        ax[1].plot(t[variable1], label= str(key))
        ax[1].xaxis.set_major_formatter(date_form)
        ax[1].grid()

    # ax[1].bar(t.index, t[variable2], label= "Precipitation")
    ax[0].set_title(variable1 + "Phase Change")
    ax[1].set_title(variable1 + "Temperature Change")
    ax[0].set_ylim(0,180)
    ax[1].set_ylim(0,180)
    ax[0].set_ylabel("Streamflow (mm)")
    plt.savefig('behaviour.pdf', format = 'pdf', bbox_inches = 'tight')

    print(str(variable1) + ' for the year ' + str(yr))

result_variability_onerow('streamflow','precip', 2005)


问:
Python - group pandas dataframe by 10 years and by month and calculate mean
In my pandas dataframe I have daily data from 2021 to 1959 (only for months April-September) and I want to calculate the mean for 10 year periods (2021 - 2012, 2011-2002, 2001-1902 and so on) for all my columns. Then I also want the mean over those 10 year periods but additionally grouped by month.

Here is my dataframe:

What I tried so far:

```<code>df_grouped = df_clean.groupby([(df_clean.index.year), (df_clean.index.month)]).mean()
</code>```

But that is only for each year and not for 10 year periods.

And this groups by decade but doesnt start at 2021 and doesn´t group by month:

```<code>df_clean.groupby((df_clean.index.year//10)*10).mean()

</code>```

I also need to do the same with the standarddeviation and at the end I want to plot everything.

Help would be gladly appreciated.

Best,
Lena

Body:
In my pandas dataframe I have daily data from 2021 to 1959 (only for months April-September) and I want to calculate the mean for 10 year periods (2021 - 2012, 2011-2002, 2001-1902 and so on) for all my columns. Then I also want the mean over those 10 year periods but additionally grouped by month.

Here is my dataframe:

What I tried so far:

df_grouped = df_clean.groupby([(df_clean.index.year), (df_clean.index.month)]).mean()

But that is only for each year and not for 10 year periods.

And this groups by decade but doesnt start at 2021 and doesn´t group by month:

df_clean.groupby((df_clean.index.year//10)*10).mean()

I also need to do the same with the standarddeviation and at the end I want to plot everything.

Help would be gladly appreciated.

Best,
Lena


问:
Office-js Word addin, Grabbing document Text
In my code below, I am attempting to grab the current documents text, set it to a variable and then use that variable in a call. My promise may not be formatted correctly but essentially the getScanResult() function uses the docBodyText variable that I set in handleClickRun(). Everytime I call it the variable is empty. Any idea as to why the document text is not being captured correctly?

```<code>const [docBodyText, setDocBodyText] = useState('');
const handleClickRun = async () => {
        return Word.run(async (context: Word.RequestContext) => {
            const docBody = context.document.body;
            docBody.load("text");
            await context.sync();
            setDocBodyText(docBody.text);
            await context.sync();
        })
        .catch(function (error) {
            console.log("Error: " + error);
            if (error instanceof OfficeExtension.Error) {
                console.log("Debug info: " + JSON.stringify(error.debugInfo));
            }
        });
    };

const handleScanResults = () => {
        new Promise(async (resolve) => {
            await handleClickRun();
            await getScanResult();
            resolve('Completed')
    })};
</code>```

I have tried using the docs and looking for other examples but have not seen any other use cases. The docs I am using is this Perhaps I can be pointed to the correct method.

I have also tried making a variable of just plain text and passing it to my api call and it works perfectly fine, so it is not a call issue.

Body:
In my code below, I am attempting to grab the current documents text, set it to a variable and then use that variable in a call. My promise may not be formatted correctly but essentially the getScanResult() function uses the docBodyText variable that I set in handleClickRun(). Everytime I call it the variable is empty. Any idea as to why the document text is not being captured correctly?

const [docBodyText, setDocBodyText] = useState('');
const handleClickRun = async () => {
        return Word.run(async (context: Word.RequestContext) => {
            const docBody = context.document.body;
            docBody.load("text");
            await context.sync();
            setDocBodyText(docBody.text);
            await context.sync();
        })
        .catch(function (error) {
            console.log("Error: " + error);
            if (error instanceof OfficeExtension.Error) {
                console.log("Debug info: " + JSON.stringify(error.debugInfo));
            }
        });
    };

const handleScanResults = () => {
        new Promise(async (resolve) => {
            await handleClickRun();
            await getScanResult();
            resolve('Completed')
    })};

I have tried using the docs and looking for other examples but have not seen any other use cases. The docs I am using is this Perhaps I can be pointed to the correct method.

I have also tried making a variable of just plain text and passing it to my api call and it works perfectly fine, so it is not a call issue.


问:
How to Create single array from nested loop?
I just want data in single array like this. I have tried to create single final array but in property i am getting same data all the time.</p>
```<code>{
    "status": 200,
    "data": [
        {
            "city": "City 1",
            "property": [
                {
                    "id": 1,

                },
                {
                    "id": 2,

                },
            ]
        },
        {
            "city": "City 2",
            "property": [
                {
                    "id": 3,
                },
                {
                    "id": 2,

                },
            ]
        },
        {
            "city": "City 3",
            "property": [
                {
                    "id": 18132,
                },
                {
                    "id": 17981,
                },
            ]
        }
    ]
}

</code>```
```<code>$custom_terms = get_terms('property_state');

    foreach($custom_terms as $custom_term) {
        wp_reset_query();
        $args = array('post_type' => 'property',
            'tax_query' => array(
                array(
                    'taxonomy' => 'property_state',
                    'field' => 'slug',
                    'terms' => $custom_term->slug,
                ),
            ),
         );

         $loop = new WP_Query($args);
         if($loop->have_posts()) {
            $city_name = $custom_term->name;
            while($loop->have_posts()) : $loop->the_post();
                $property[] =  array(
                   'id' => get_the_ID(),
                 );
            endwhile;
         }
            $final[] = array('city' =>$city_name, 'property' => $property);
    }

</code>```

Body:
I just want data in single array like this. I have tried to create single final array but in property i am getting same data all the time.

{
    "status": 200,
    "data": [
        {
            "city": "City 1",
            "property": [
                {
                    "id": 1,

                },
                {
                    "id": 2,

                },
            ]
        },
        {
            "city": "City 2",
            "property": [
                {
                    "id": 3,
                },
                {
                    "id": 2,

                },
            ]
        },
        {
            "city": "City 3",
            "property": [
                {
                    "id": 18132,
                },
                {
                    "id": 17981,
                },
            ]
        }
    ]
}

$custom_terms = get_terms('property_state');

    foreach($custom_terms as $custom_term) {
        wp_reset_query();
        $args = array('post_type' => 'property',
            'tax_query' => array(
                array(
                    'taxonomy' => 'property_state',
                    'field' => 'slug',
                    'terms' => $custom_term->slug,
                ),
            ),
         );

         $loop = new WP_Query($args);
         if($loop->have_posts()) {
            $city_name = $custom_term->name;
            while($loop->have_posts()) : $loop->the_post();
                $property[] =  array(
                   'id' => get_the_ID(),
                 );
            endwhile;
         }
            $final[] = array('city' =>$city_name, 'property' => $property);
    }


问:
Is it Possible to Recreate an Excel Template in C#?
The template I am attempting to recreate is this: Template

I have started the process of attempting to recreate the template, but I am mainly having issues with cell structure and inserting data into the cells. So I am not sure if I am wasting my time trying to do something that might not be possible.

```<code>  private void excelcreator()
        {
            Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
            app.Visible = true;
            app.Interactive = false;
            Microsoft.Office.Interop.Excel.Workbook wb = app.Workbooks.Add(1);
            Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets[1];

            ws.Range["B7"].EntireRow.Font.Size = 14;
            Range line = (Range)ws.Rows[1];
            line.Insert();
            ws.Range[ws.Cells[7, 2], ws.Cells[7, 4]].Merge();
            app.Cells[7, 2] = "Date";
            app.Interactive = true;
            // AutoSet Cell Widths to Content Size
            ws.Cells.Select();
            ws.Cells.EntireColumn.AutoFit();
            ws.PageSetup.TopMargin = 0;
            ws.PageSetup.BottomMargin = 0;
            ws.PageSetup.LeftMargin = 0;
            ws.PageSetup.RightMargin = 0;
            ws.Range[7, 2].EntireRow.Font.Bold = true;
            ws.PageSetup.Orientation = XlPageOrientation.xlLandscape;
        }
</code>```

I am also getting an error on the line ws.Range[7, 2].EntireRow.Font.Bold = true; that says: System.Runtime.InteropServices.COMException: 'Exception from HRESULT: 0x800A03EC'"

Body:
The template I am attempting to recreate is this: Template

I have started the process of attempting to recreate the template, but I am mainly having issues with cell structure and inserting data into the cells. So I am not sure if I am wasting my time trying to do something that might not be possible.

  private void excelcreator()
        {
            Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
            app.Visible = true;
            app.Interactive = false;
            Microsoft.Office.Interop.Excel.Workbook wb = app.Workbooks.Add(1);
            Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets[1];

            ws.Range["B7"].EntireRow.Font.Size = 14;
            Range line = (Range)ws.Rows[1];
            line.Insert();
            ws.Range[ws.Cells[7, 2], ws.Cells[7, 4]].Merge();
            app.Cells[7, 2] = "Date";
            app.Interactive = true;
            // AutoSet Cell Widths to Content Size
            ws.Cells.Select();
            ws.Cells.EntireColumn.AutoFit();
            ws.PageSetup.TopMargin = 0;
            ws.PageSetup.BottomMargin = 0;
            ws.PageSetup.LeftMargin = 0;
            ws.PageSetup.RightMargin = 0;
            ws.Range[7, 2].EntireRow.Font.Bold = true;
            ws.PageSetup.Orientation = XlPageOrientation.xlLandscape;
        }

I am also getting an error on the line ws.Range[7, 2].EntireRow.Font.Bold = true; that says: System.Runtime.InteropServices.COMException: 'Exception from HRESULT: 0x800A03EC'"


问:
Django UpdateView set read only field by user permission
I have seen some posts like Making form fields - read only or disabled in DJANGO updateView use custom form on an UpdateView to make some fields as read only fields. However, the form object is not accessible for request.user object. If I want to make some fields read-only only for some user group, is there way to do it under UpdateView?</p>


问:
Problem of the traveler in the desert, greedy and dynamic approach
A traveler in a desert wants to go from one oasis to another until a final destination without taking the risk of dying from thirst (i.e. lack of water). He know the position of all the oases from his starting point to his final destination. The traveler needs to drink one liter of wa for each kilometer made. When he leaves his starting point, he has a bottle full of water. When he reaches an oasis,he has two possibilites :

1 - continue his trip
2 - stop and refill his bottle of water to the max

each oasis, the traveler has to pay (say in euros) to a watchmen the quantity of water lost in each oasis. More precisely, he has to pay an amount equivalent to the squared of the number of liters of water emptied form the bottle when he stops and refills his bottle. We also to take into account the quantity of water emptied at the final destination. The problem now is then to find a solution in order to pay the minimum amount of money

a) Propose a greedy approach. Is it optimal ?

We propose to build a solution based on the dynamic programming paradigm. Your solution must consider the following quantities (note accessible points depend on the value of C)

paid(i) : minimum amount of money paid from the starting point to point i when the traveler empties his bottle at point i - This the wuantity we want to optimize

d(i,j) : number of kilometers between point i and point j

C : the capacity of the bottle

Qustions :
1 - Give the structure of an optimal solution (and if possible prove its optimality)
2 - Give a recursive definition of the optimal value paid
3 - Provide an algorithme for finding the solution in polynomial time. You must provide a complete pseudo-code for all solution. Give the complexity (time and space)
4 - Provide an approach for computing the solution (i.e the trip)
5 - Apply yout algorithme to the following example : the bottle has a capacity of 10 liters, and source points located at 8, 9, 16, 18, 24, 27 kilometers from starting point and such that the final point is at 32 kilometers from the starting point

i would like to do a greedy algorithm and a dynamic algorithm, and i can't. I first tried to do the greedy approach

def _cost(lastStop, d, Cmax, i) :

    if i == len(d)-1 :
        return (d[i]-lastStop)**2

    current = d[i]
    next = d[i+1]
    price = (Cmax-(lastStop-current))**2

    #We have water left
    if (next-lastStop) >= 0 :
        return min(_cost(lastStop, d, Cmax, i+1), _cost(current, d, Cmax, i+1) + price)
    #We don't have enough water we have to stop and refuel
    else :
        return _cost(current, d, Cmax, i+1) + price

def cost(d, Cmax) :

    return _cost(d[0],d,Cmax,0)

d = [8, 9, 16, 18, 24, 27, 32]
Cmax = 10

print(cost(d,Cmax))
```


问:
Configure SMTP using Powershell (IP and Port)
I am trying to configure SMTP since I set it up on servers all the time and most of the settings are similar, I have some of it down but cant get everything changed the way I want even after going through all the settings. I can get things like maximum message size, smart host, FQDN but cant change the IP, port, or enable logging. I could definitely just be missing settings but I feel like I've been through them all.

I got most of it working like changing the smart host using:

```<code>$smtpserversetting = get-wmiobject -namespace root\MicrosoftIISv2 -computername localhost -Query "Select * from IIsSmtpServerSetting"

$smtpserversetting.MaxMessageSize="10485760"

$smtpserversetting.SmartHost="smtp.office365.com"
$smtpserversetting.FullyQualifiedDomainName="myFQDN.com"

$smtpserversetting.put()

</code>```

That's not everything I'm changing but that's the method I'm using. However the thing I cant get is this IIS 6 IP and logging

I cant find the settings anywhere for this tab at all. I just want to change the IP to the server I'm on, change the port to 587 and set up logging. To be clear I dont need to send an SMTP email just want to configure then I can test outside powershell. Any help would be appreciated.

Body:
I am trying to configure SMTP since I set it up on servers all the time and most of the settings are similar, I have some of it down but cant get everything changed the way I want even after going through all the settings. I can get things like maximum message size, smart host, FQDN but cant change the IP, port, or enable logging. I could definitely just be missing settings but I feel like I've been through them all.

I got most of it working like changing the smart host using:

$smtpserversetting = get-wmiobject -namespace root\MicrosoftIISv2 -computername localhost -Query "Select * from IIsSmtpServerSetting"

$smtpserversetting.MaxMessageSize="10485760"

$smtpserversetting.SmartHost="smtp.office365.com"
$smtpserversetting.FullyQualifiedDomainName="myFQDN.com"

$smtpserversetting.put()

That's not everything I'm changing but that's the method I'm using. However the thing I cant get is this IIS 6 IP and logging

I cant find the settings anywhere for this tab at all. I just want to change the IP to the server I'm on, change the port to 587 and set up logging. To be clear I dont need to send an SMTP email just want to configure then I can test outside powershell. Any help would be appreciated.


问:
Detect firstChild of ActivateRoute changed
I'm having a scenario that I want to subscribe to the child route params but at the initialize of my parent component there is no firstChild, just after clicking an element with routerLink the children component renders. So I need a way to know that the firstChild on the ActivatedRoute is changed.

This is my parent component:

```<code>@Component({
    selector: 'app-parent',
    templateUrl: './parent.component.html',
    styleUrls: ['./parent.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ParentComponent {
    public items: number[] = [1, 2, 3, 4];

    public constructor(
        private activatedRoute: ActivatedRoute,
    ) {
        this.activatedRoute.firstChild?.params.subscribe(params => console.log(params));
    }
}
</code>```

And it's template:

```<code><ul *ngFor="let item of items">
   <li [routerLink]="[item]">{{item}}</li>
</ul>

<router-outlet></router-outlet>
</code>```

And this is my routes setup:

```<code>const routes: Routes = [
    {
        path: '',
        component: ParentComponent,
        children: [
            {
                path: ':id',
                component: ChildComponent,
            },
        ],
    },
];
</code>```

Body:
I'm having a scenario that I want to subscribe to the child route params but at the initialize of my parent component there is no firstChild, just after clicking an element with routerLink the children component renders. So I need a way to know that the firstChild on the ActivatedRoute is changed.

This is my parent component:

@Component({
    selector: 'app-parent',
    templateUrl: './parent.component.html',
    styleUrls: ['./parent.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ParentComponent {
    public items: number[] = [1, 2, 3, 4];

    public constructor(
        private activatedRoute: ActivatedRoute,
    ) {
        this.activatedRoute.firstChild?.params.subscribe(params => console.log(params));
    }
}

And it's template:

{{item}}

<router-outlet></router-outlet>

And this is my routes setup:

const routes: Routes = [
    {
        path: '',
        component: ParentComponent,
        children: [
            {
                path: ':id',
                component: ChildComponent,
            },
        ],
    },
];


问:
How can I find the General Forms of Estimable functions for a certain General Linear Model in R?
When calling the 'glm' procedure in SAS, it provides you with a general form of the basic estimable functions for an overparametrized model, for example:

```<code>Effect           Coefficients
Intercept        L1
diet        A    L2
diet        B    L3
diet        C    L1-L2-L3
</code>```

Is there a function or package in R that can provide a similar output?

So far I have only found the estimability package, which only seems to provide a test for wether or not certain contrasts are estimable.

Body:
When calling the 'glm' procedure in SAS, it provides you with a general form of the basic estimable functions for an overparametrized model, for example:

Effect           Coefficients
Intercept        L1
diet        A    L2
diet        B    L3
diet        C    L1-L2-L3

Is there a function or package in R that can provide a similar output?

So far I have only found the estimability package, which only seems to provide a test for wether or not certain contrasts are estimable.


问:
CRichEditCtrl::StreamIn works with x86 compile but not x64
I am writing in C++ using MFC under Visual Studio 2022.
I have a CRichEditCtrl embedded in a dialog, and I want to feed it pre-formatted text markup written with an external RTF editor. In the end I want to embed the text within the program (to avoid having an external file), and so far as I can see the only way to do this is by putting the text into a CMemFile and then using CRichEditCtrl::StreamIn. If there is a better way of doing this I'd like to hear about it.

However, to start off I just tried to read from an external RFT file using the example code from the MSoft documentation.

For completion, here is my code version:

```<code>CFile cFile(TEXT("NeuroSimHelp.rtf"), CFile::modeRead);
EDITSTREAM es;
es.dwCookie = (DWORD)&cFile;
es.pfnCallback = FileStreamInCallback;
m_HelpRTF.StreamIn(SF_RTF, es);
</code>```
```<code>static DWORD CALLBACK FileStreamInCallback(DWORD dwCookie, LPBYTE pbBuff, LONG cb, LONG* pcb);
</code>```
```<code>static DWORD CALLBACK FileStreamInCallback(DWORD dwCookie, LPBYTE pbBuff, LONG cb, LONG* pcb)
{
    CFile* pFile = (CFile*)dwCookie;
    *pcb = pFile->Read(pbBuff, cb);
    return 0;
}
</code>```

This compiles and runs fine in x86 mode, but fails to compile in x64 mode.

The problem lies in the line:
es.pfnCallback = FileStreamInCallback;

which generates the compile error:

error C2440: '=': cannot convert from 'DWORD (__cdecl *)(DWORD,LPBYTE,LONG,LONG *)' to 'EDITSTREAMCALLBACK'

As I said, this compiles and works in x86, so I guess the 64-bit callback function address does not fit into the DWORD_PTR dwCookie in EDITSTREAMCALLBACK type.

I'm probably missing something obvious, but if anyone knows how to fix this the  help would be much appreciated.
Thanks,
Bill H

Body:
I am writing in C++ using MFC under Visual Studio 2022.
I have a CRichEditCtrl embedded in a dialog, and I want to feed it pre-formatted text markup written with an external RTF editor. In the end I want to embed the text within the program (to avoid having an external file), and so far as I can see the only way to do this is by putting the text into a CMemFile and then using CRichEditCtrl::StreamIn. If there is a better way of doing this I'd like to hear about it.

However, to start off I just tried to read from an external RFT file using the example code from the MSoft documentation.

For completion, here is my code version:

CFile cFile(TEXT("NeuroSimHelp.rtf"), CFile::modeRead);
EDITSTREAM es;
es.dwCookie = (DWORD)&cFile;
es.pfnCallback = FileStreamInCallback;
m_HelpRTF.StreamIn(SF_RTF, es);

static DWORD CALLBACK FileStreamInCallback(DWORD dwCookie, LPBYTE pbBuff, LONG cb, LONG* pcb);

static DWORD CALLBACK FileStreamInCallback(DWORD dwCookie, LPBYTE pbBuff, LONG cb, LONG* pcb)
{
    CFile* pFile = (CFile*)dwCookie;
    *pcb = pFile->Read(pbBuff, cb);
    return 0;
}

This compiles and runs fine in x86 mode, but fails to compile in x64 mode.

The problem lies in the line:
es.pfnCallback = FileStreamInCallback;

which generates the compile error:

error C2440: '=': cannot convert from 'DWORD (__cdecl *)(DWORD,LPBYTE,LONG,LONG *)' to 'EDITSTREAMCALLBACK'

As I said, this compiles and works in x86, so I guess the 64-bit callback function address does not fit into the DWORD_PTR dwCookie in EDITSTREAMCALLBACK type.

I'm probably missing something obvious, but if anyone knows how to fix this the  help would be much appreciated.
Thanks,
Bill H


问:
How to have multiple options when I tried to create a class using flutter?
This is what I mean:

enter image description here

and in my Visual Studio Code, I only have the option “add 'late' modifier”

How can I have all the options from the screen in my Visual Studio Code?

Thanks


问:
how to stop iMessage link preview from rotating image
When sharing links from my website, sometimes the images are rotated 90 degrees.

```<code>https://dw2h1frcjb7pw.cloudfront.net/1a5765ac5b5e7c0356a5eaf208c53a290fd8497ef1907e32212888f1c2094cbd
</code>```

https://primitives.xyz/claim/1aE14KJuHOQKkbP5cjtMsV

How do I fix this? In all my extensions for testing previews it displays correctly.

Body:
When sharing links from my website, sometimes the images are rotated 90 degrees.

https://dw2h1frcjb7pw.cloudfront.net/1a5765ac5b5e7c0356a5eaf208c53a290fd8497ef1907e32212888f1c2094cbd

https://primitives.xyz/claim/1aE14KJuHOQKkbP5cjtMsV

How do I fix this? In all my extensions for testing previews it displays correctly.


问:
Giving names for excel files programatically with pandas ExcelWriter
How can I give file name programmatically for excelwriter of pandas
i.e.
the name below 'filename.xlsx':  I need to define/change it within the code

```<code>results_to_export =[.......]

excel_file_name = pandas.ExcelWriter('filename.xlsx')

results_to_export.to_excel(excel_file_name)

excel_file_name.save()
</code>```

Thanks

I tried the thing above

Body:
How can I give file name programmatically for excelwriter of pandas
i.e.
the name below 'filename.xlsx':  I need to define/change it within the code

results_to_export =[.......]

excel_file_name = pandas.ExcelWriter('filename.xlsx')

results_to_export.to_excel(excel_file_name)

excel_file_name.save()

Thanks

I tried the thing above


问:
Submit form with radio buttons generated from an array
I have a list of radio buttons for guests to select whether they're attending an event or not.

A party can have several members, so multiple yes/no options can exist on the same page.

Idea is that a person can go down the list and hit yes or no on guest attendance. I am then trying to segment out the names of those who have accepted and declined into arrays, so I can push it to wpdb.

I have the following that generated the radio options:

```<code><?php
foreach ($results as $result) {
    $party = $result['party']; // "John, Doe" in DB varchar
    $party_guests = explode(",", $party);

    $attending_array = array();
    $not_attending_array = array();

    foreach ($party_guests as $index => $guest){
        ?>
        <span class="guest__name"><?php echo $guest; ?></span>
        <div class="guest__options-option">
            <span>Attending?</span>
            <div class="guest__options-group">
                <input class="guest__attendance-input" id="attending_array[<?php echo $index; ?>]" type="radio" name="attending-<?php echo $index; ?>" value="<?php echo $guest; ?>" required/>
                <label for="attending-yes-<?php echo $index; ?>">Yes</label>
            </div>
            <div class="guest__options-group">
                <input class="guest__attendance-input" id="attending_array[<?php echo $index; ?>]" type="radio"  name="attending-<?php echo $index; ?>" value="<?php echo $guest; ?>" required/>
                <label for="attending-no-<?php echo $index; ?>">No</label>
            </div>
        </div>
        <?php
    }
}
?>
</code>```

But I cannot see a way in which I can (via PHP) dynamically add the names to the attending_array or not_ attending_array?

How can I do an array_push based on what option the user clicks on? I cannot target a specific name because $party may contain 2 guest, 6 guest etc.

Body:
I have a list of radio buttons for guests to select whether they're attending an event or not.

A party can have several members, so multiple yes/no options can exist on the same page.

Idea is that a person can go down the list and hit yes or no on guest attendance. I am then trying to segment out the names of those who have accepted and declined into arrays, so I can push it to wpdb.

I have the following that generated the radio options:

<?php
foreach ($results as $result) {
    $party = $result['party']; // "John, Doe" in DB varchar
    $party_guests = explode(",", $party);

    $attending_array = array();
    $not_attending_array = array();

    foreach ($party_guests as $index => $guest){
        ?>
        <?php echo $guest; ?>

            Attending?

                <input class="guest__attendance-input" id="attending_array[<?php echo $index; ?>]" type="radio" name="attending-<?php echo $index; ?>" value="<?php echo $guest; ?>" required/>
                <label for="attending-yes-<?php echo $index; ?>">Yes

                <input class="guest__attendance-input" id="attending_array[<?php echo $index; ?>]" type="radio"  name="attending-<?php echo $index; ?>" value="<?php echo $guest; ?>" required/>
                <label for="attending-no-<?php echo $index; ?>">No

        <?php
    }
}
?>

But I cannot see a way in which I can (via PHP) dynamically add the names to the attending_array or not_ attending_array?

How can I do an array_push based on what option the user clicks on? I cannot target a specific name because $party may contain 2 guest, 6 guest etc.


问:
How we can record other side video call streams video with voice in webrtc in ReactJs?
When i am answering the call then i want to record this video stream, how can i record in react js with audio of both sides.

```<code>  const answerCall = () => {
    toast.success(`Answered...`);
    setCallAccepted(true);

    const peer = new Peer({ initiator: false, trickle: false, stream });

    peer.on('signal', (data) => {
      socket.emit('answerCall', { signal: data, to: call.from });
    });

    peer.on('stream', (currentStream) => {
      userVideo.current.srcObject = currentStream;
      setUserStream(currentStream);
    });

    peer.signal(call.signal);

    connectionRef.current = peer;
  };
</code>```

There are some issues on recording.....

Body:
When i am answering the call then i want to record this video stream, how can i record in react js with audio of both sides.

  const answerCall = () => {
    toast.success(`Answered...`);
    setCallAccepted(true);

    const peer = new Peer({ initiator: false, trickle: false, stream });

    peer.on('signal', (data) => {
      socket.emit('answerCall', { signal: data, to: call.from });
    });

    peer.on('stream', (currentStream) => {
      userVideo.current.srcObject = currentStream;
      setUserStream(currentStream);
    });

    peer.signal(call.signal);

    connectionRef.current = peer;
  };

There are some issues on recording.....


问:
Autogeneration of readonly Swift protocol exposing @Published properties
I'm currently working on a refactor where write access to model objects is restricted.  Model objects are reference types with @Published properties:

```<code>public final class Model {
  public enum State { /* Some cases here. */ }
  @Published public var state: State
}
</code>```

Let's say that I want a view model that returns a string to be observed by the UI layer.  I'm using a protocol to expose readonly access to the view model, and a concrete implementation to support it:

```<code>public protocol ViewModelAPI {
  var stringPublisher: AnyPublisher<String, Never> { get }
}

private struct ViewModel: ViewModelAPI {
  public let stringPublisher: AnyPublisher<String, Never>
  init(model: Model) {
    stringPublisher =
      model.$state
      .map { /* Convert Model.State to string to display. */ }
      .eraseToAnyPublisher()
  }
}

public final class StateStringView: UIView {
  init(viewModel: ViewModelAPI) {
    /* Subscribe to `viewModel` to observe new String to display. */
  }
}
</code>```

Generally, this approach works pretty well, in that it prevents the UI layer from having direct Model dependencies.  However, the ViewModel implementation has access to the settable Model.state property even though it only ever reads the property and never sets it.

Ideally, I'd like an easy way to create a protocol from an existing model object, such that we convert any @Published property into an AnyPublisher allowing readonly access.  I think creating a protocol by hand is appropriate for ViewModel APIs since it's tailored to specifically the data used by a single UI feature.  However, creating explicit observable protocols for all Model objects seems like a lot of overhead since it would require updating the protocol whenever the Model is updated.

Does anyone have any ideas on how to generate a protocol such that we could inspect a class and extract all of the @Published properties?  Would dynamic member lookup be a possible solution here?  Or would I just need to use a script to generate protocols that accomplish this?

Body:
I'm currently working on a refactor where write access to model objects is restricted.  Model objects are reference types with @Published properties:

public final class Model {
  public enum State { /* Some cases here. */ }
  @Published public var state: State
}

Let's say that I want a view model that returns a string to be observed by the UI layer.  I'm using a protocol to expose readonly access to the view model, and a concrete implementation to support it:

public protocol ViewModelAPI {
  var stringPublisher: AnyPublisher<String, Never> { get }
}

private struct ViewModel: ViewModelAPI {
  public let stringPublisher: AnyPublisher<String, Never>
  init(model: Model) {
    stringPublisher =
      model.$state
      .map { /* Convert Model.State to string to display. */ }
      .eraseToAnyPublisher()
  }
}

public final class StateStringView: UIView {
  init(viewModel: ViewModelAPI) {
    /* Subscribe to `viewModel` to observe new String to display. */
  }
}

Generally, this approach works pretty well, in that it prevents the UI layer from having direct Model dependencies.  However, the ViewModel implementation has access to the settable Model.state property even though it only ever reads the property and never sets it.

Ideally, I'd like an easy way to create a protocol from an existing model object, such that we convert any @Published property into an AnyPublisher allowing readonly access.  I think creating a protocol by hand is appropriate for ViewModel APIs since it's tailored to specifically the data used by a single UI feature.  However, creating explicit observable protocols for all Model objects seems like a lot of overhead since it would require updating the protocol whenever the Model is updated.

Does anyone have any ideas on how to generate a protocol such that we could inspect a class and extract all of the @Published properties?  Would dynamic member lookup be a possible solution here?  Or would I just need to use a script to generate protocols that accomplish this?


问:
Milkdown Editor get latest change
Iam trying to make an CollabEditor myself, now i want to get the changes from the editor.
But iam only able to get the full markdown or json.

If the user types "Hello" i want to get:

//string is the add string, start is the index where it got added

change: {string:'H', start:0}

change: {string:'e', start:1}

change: {string:'l', start:2}

change: {string:'l', start:3}

change: {string:'o', start:4}

It is possible that the user pastes the string then it should output:

change: {string:'Hello', start:0}

On delete it should output:

//from delet from, to index

change: {from:0, to:4}

Maybe someone knows how this could work with the MilkdownEditor

Title: Milkdown Editor get latest change


问:
error: 'InetPton' was not declared in this scope while compiling c++
I'm new to c++ and when I try to compile the code, I get the following:

In file included from C:\Users\Toqa\Documents\Keylogger\main.cpp:10:
C:\Users\Toqa\Documents\Keylogger\SendData.h: In constructor
'Data::Data()': C:\Users\Toqa\Documents\Keylogger\SendData.h:34:13:
error: 'InetPton' was not declared in this scope InetPton(AF_INET,
"172.0.0.1", &addr.sin_addr.s_addr); ^~~~~~~~
C:\Users\Toqa\Documents\Keylogger\SendData.h:34:13: note: suggested
alternative: 'inet_ntoa' InetPton(AF_INET, "172.0.0.1",
&addr.sin_addr.s_addr); ^~~~~~~~ inet_ntoa

This is my code:

```<code>#ifndef SENDDATA_H
#define SENDDATA_H

#include <winsock2.h>
#include <ws2tcpip.h>

#include "IO.h"

#include<iostream>
#include<fstream>
#include<stdio.h>
#include <unistd.h>
#include <stdlib.h>

class Data{
    std::fstream file;

    int general_socket_descriptor;

    struct sockaddr_in address;
    int address_length;

    WSADATA wsa_data;
    SOCKADDR_IN addr;

    int server;

    public:
        Data(){
            create_socket();

            InetPton(AF_INET, "172.0.0.1", &addr.sin_addr.s_addr);

            addr.sin_family = AF_INET;
            addr.sin_port = htons(55555);

            create_connection();

            std::string path = IO::GetOurPath(true);

            file.open(path + "test.txt", std::ios::in | std::ios::binary);
            if(file.is_open()){
                std::cout<<"[LOG] : File Ready...\n";
            }
            else{
                std::cout<<"[ERROR] : File creation failed, Exiting.\n";
            }
        }

        void create_socket(){
            WSAStartup(MAKEWORD(2, 0), &wsa_data);

            if (server = socket(AF_INET, SOCK_STREAM, 0)) {
                std::cout<<"[LOG] : Socket Created Successfully.\n";
            }
            else{
                perror("[ERROR] : Socket failed.\n");
            }

        }

        void create_connection(){

            if (connect(server, reinterpret_cast<SOCKADDR *>(&addr), sizeof(addr)) < 0) {
                perror("[ERROR] : connection attempt failed.\n");
            }
            std::cout<<"[LOG] : Connection Successfull.\n";
        }

        void transmit_file(){
            std::string contents((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
            std::cout<<"[LOG] : Transmission Data Size "<<contents.length()<<" Bytes.\n";

            std::cout<<"[LOG] : Sending...\n";

            int bytes_sent = send(server , contents.c_str() , contents.length() , 0 );
            std::cout<<"data: "<<contents.c_str()<<"\n end \n";
            std::cout<<"[LOG] : Transmitted Data Size "<<bytes_sent<<" Bytes.\n";

            std::cout<<"[LOG] : File Transfer Complete.\n";

        }

};

#endif // SENDDATA_H

</code>```

I'm using code blocks IDE on windows and this is the command of compiling:
g++.exe  -o bin\Debug\Test.exe obj\Debug\main.o  -mwindows  -lws2_32

The version is:
g++ (x86_64-posix-seh-rev0, Built by MinGW-W64 project) 8.1.0

After researching the error, most of the solutions were ensuring to link it with ws2_32. However, I'm using it and I still get the same error.

Body:
I'm new to c++ and when I try to compile the code, I get the following:

In file included from C:\Users\Toqa\Documents\Keylogger\main.cpp:10:
C:\Users\Toqa\Documents\Keylogger\SendData.h: In constructor
'Data::Data()': C:\Users\Toqa\Documents\Keylogger\SendData.h:34:13:
error: 'InetPton' was not declared in this scope InetPton(AF_INET,
"172.0.0.1", &addr.sin_addr.s_addr); ^~~~~~~~
C:\Users\Toqa\Documents\Keylogger\SendData.h:34:13: note: suggested
alternative: 'inet_ntoa' InetPton(AF_INET, "172.0.0.1",
&addr.sin_addr.s_addr); ^~~~~~~~ inet_ntoa

This is my code:

#ifndef SENDDATA_H
#define SENDDATA_H

#include <winsock2.h>
#include <ws2tcpip.h>

#include "IO.h"

#include<iostream>
#include<fstream>
#include<stdio.h>
#include <unistd.h>
#include <stdlib.h>

class Data{
    std::fstream file;

    int general_socket_descriptor;

    struct sockaddr_in address;
    int address_length;

    WSADATA wsa_data;
    SOCKADDR_IN addr;

    int server;

    public:
        Data(){
            create_socket();

            InetPton(AF_INET, "172.0.0.1", &addr.sin_addr.s_addr);

            addr.sin_family = AF_INET;
            addr.sin_port = htons(55555);

            create_connection();

            std::string path = IO::GetOurPath(true);

            file.open(path + "test.txt", std::ios::in | std::ios::binary);
            if(file.is_open()){
                std::cout<<"[LOG] : File Ready...\n";
            }
            else{
                std::cout<<"[ERROR] : File creation failed, Exiting.\n";
            }
        }

        void create_socket(){
            WSAStartup(MAKEWORD(2, 0), &wsa_data);

            if (server = socket(AF_INET, SOCK_STREAM, 0)) {
                std::cout<<"[LOG] : Socket Created Successfully.\n";
            }
            else{
                perror("[ERROR] : Socket failed.\n");
            }

        }

        void create_connection(){

            if (connect(server, reinterpret_cast<SOCKADDR *>(&addr), sizeof(addr)) < 0) {
                perror("[ERROR] : connection attempt failed.\n");
            }
            std::cout<<"[LOG] : Connection Successfull.\n";
        }

        void transmit_file(){
            std::string contents((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
            std::cout<<"[LOG] : Transmission Data Size "<<contents.length()<<" Bytes.\n";

            std::cout<<"[LOG] : Sending...\n";

            int bytes_sent = send(server , contents.c_str() , contents.length() , 0 );
            std::cout<<"data: "<<contents.c_str()<<"\n end \n";
            std::cout<<"[LOG] : Transmitted Data Size "<<bytes_sent<<" Bytes.\n";

            std::cout<<"[LOG] : File Transfer Complete.\n";

        }

};

#endif // SENDDATA_H

I'm using code blocks IDE on windows and this is the command of compiling:
g++.exe  -o bin\Debug\Test.exe obj\Debug\main.o  -mwindows  -lws2_32

The version is:
g++ (x86_64-posix-seh-rev0, Built by MinGW-W64 project) 8.1.0

After researching the error, most of the solutions were ensuring to link it with ws2_32. However, I'm using it and I still get the same error.


问:
Is there a way to stave off the 'script taking too long' error?
I've got a page that renders a lot of data and hits the 'script taking too long' wall.

This is a personal project, so I'm not concerned about user experience.

When I 'comment out' 20% of the data it runs fine, it's just the last few bunch of points that push it over the edge. It times out after - I dunno - 15 seconds?

I have experimented with optimizing the rendering - including various attempts to thin out the data - and it turns out that's going to be more work than I have time for right now, I'd really just like to get the render working for now and circle back.

Is there anything I can do to defeat - or at least temporarily adjust the duration of - that timeout? I am using Chrome. Hoping there's some configuration or developer setting or something.


问:
How can I add an event listener on one area of the page?
I have an event listener on page 1

```<code>window.addEventListener("keydown")
</code>```

It's causing me issues where another event listener "keydown" in a dialog on that page 1 is conflicting with the window event listener.

So dialog event listener
Page event listener

When I add text to the dialog, the page picks up that keydown. I don't want that. I can't add stopPropagation to the page then the dialog won't get the backspace.

What should I do? Can I replace the window. part to something more specific?

Body:
I have an event listener on page 1

window.addEventListener("keydown")

It's causing me issues where another event listener "keydown" in a dialog on that page 1 is conflicting with the window event listener.

So dialog event listener
Page event listener

When I add text to the dialog, the page picks up that keydown. I don't want that. I can't add stopPropagation to the page then the dialog won't get the backspace.

What should I do? Can I replace the window. part to something more specific?


问:
Webpack globed list of files and make them accessible to main entry
I am trying to find a way to provide the Webpack configuration a list of files to bundle with the primary entry and make the contents of those files importable. Here is a rough example of code to try to explain. I have all the files at the time of bundling. I just for the life of me cannot figure out how to bridge this gap.

```<code>// ./webpack-config-builder
const glob = require('glob');

function buildConfig(supportFiles/* I want to get this into the bundle somehow*/) {
    return {
        // additional Webpack config
        entry: {
            primary: './primary.js',
        }
        // additional Webpack config
    };
}

const globedFiles = glob('**/*.support.js');

buildConfig(globedFiles);

// ./primary.js
import getSupportFile from './get-support-file';

console.log(getSupportFile('foo').message);

// ./get-support-file
const supportFiles; // Somehow the support files have been transpiled and bundled and are avaliable here

const processedFiles = reduce(
    supportFiles,
    (acc, fileData) => {
        acc[fileData.id] = fileData;

        return acc;
    },
    {}
);

function getSupportFile(fileId) {
    return processedFiles[fileId];
}

export default getSupportFile;

// ./exampleA/example.support.js
const support = {
    fileId: 'foo',
    message: 'You got this!'
};

export default support;

// ./exampleB/example.support.js
const support = {
    fileId: 'bar',
    message: 'You did it!'
};

export default support;
</code>```

I truly am sorry for the complex question. I am convinced that this should be possible but I am not sure what to even look for online or even how to ask the correct question.

Does anyone have any ideas where to continue my search or any ideas on how to better refine what I am trying to do?

Body:
I am trying to find a way to provide the Webpack configuration a list of files to bundle with the primary entry and make the contents of those files importable. Here is a rough example of code to try to explain. I have all the files at the time of bundling. I just for the life of me cannot figure out how to bridge this gap.

// ./webpack-config-builder
const glob = require('glob');

function buildConfig(supportFiles/* I want to get this into the bundle somehow*/) {
    return {
        // additional Webpack config
        entry: {
            primary: './primary.js',
        }
        // additional Webpack config
    };
}

const globedFiles = glob('**/*.support.js');

buildConfig(globedFiles);

// ./primary.js
import getSupportFile from './get-support-file';

console.log(getSupportFile('foo').message);

// ./get-support-file
const supportFiles; // Somehow the support files have been transpiled and bundled and are avaliable here

const processedFiles = reduce(
    supportFiles,
    (acc, fileData) => {
        acc[fileData.id] = fileData;

        return acc;
    },
    {}
);

function getSupportFile(fileId) {
    return processedFiles[fileId];
}

export default getSupportFile;

// ./exampleA/example.support.js
const support = {
    fileId: 'foo',
    message: 'You got this!'
};

export default support;

// ./exampleB/example.support.js
const support = {
    fileId: 'bar',
    message: 'You did it!'
};

export default support;

I truly am sorry for the complex question. I am convinced that this should be possible but I am not sure what to even look for online or even how to ask the correct question.

Does anyone have any ideas where to continue my search or any ideas on how to better refine what I am trying to do?


问:
How do I update to Bootstrap 5 in a ASP.NET Web Forms App?
I would like to update to bootstrap 5, but when I try to update I get this error message:

"Unable to resolve dependencies. 'bootstrap 5.2.2' is not compatible with 'AspNet.ScriptManager.bootstrap 4.6.0 constraint: bootstrap (>= 4.5.9 && < 4.6.1)'."

I found this What does AspNet.ScriptManager.bootstrap do? but I don't fully understand it. When I tried to implement the code suggested in that answer, I just get even more errors.


问:
How to change data directory for Docker Rootless?
The only info about rootless data dir on the official Docker Docs website is:

The data dir is set to ~/.local/share/docker by default. The data dir should not be on NFS.

However I didn't found any option to change this during installation via dockerd-rootless-setuptool.sh install

Change default data directory for Docker on non-root user (rootless mode).


问:
Geometry is an OSMnx network
I am using OSMnx to download and simplify a road network. But the problem I have is that once I simplify, I cannot preserve the precise geometry/geospatial information of links. The following figure shows the road network drawn from the road network in graph format
Road Network from graph

But the interesting fact is if I convert the same network to geodataframe, then that geodataframe has the exact linestring of links like the following figure,
Road network from gdf

I want to save the downloaded and simplified road network in .osm format with preserved geometry/geospatial information of links.

I tried to save the road network in .osm format with the pristine geospatial information of links. But the simplified network in a .osm/graphml format does not have that. But the saved network in .gpkg format has the pristine linestring.

Title: Geometry is an OSMnx network


Title: Need help unesting/flattening a field twice within the same row

Body:
I'm fairly new to PostgreSQL and have a situation where I need to flatten a text column to two separate columns.

Below is the query I'm using:

SELECT s.CoolerShelf,
s.ShelfPosition,
FROM planogram
CROSS JOIN LATERAL UNNEST(string_to_array(shelves, ','))
WITH ORDINALITY s(CoolerShelf,ShelfPosition)

The desired results should look like as follows:

coolershelf                        shelfposition
[["8d2cf35d-5708-45e0-9cb6-acad358e0f92" 0
"5a91f7a2-029a-46d7-8440-9337dd1b87d3" 1
"521562a9-9d33-438d-8156-1e6b1874ec8e" 2
"e14817e4-6630-4dca-a188-ac71060dcac9" 3
"76967052-ba9d-43f5-afd4-b4bbe1452d7e" 4
"2e5a6fb2-071e-426b-ac55-69f16baa0b42" 5
"108f263d-ee78-4124-a94b-2c5641f90321" 6
"0dbe5016-9e78-4173-b6e6-ff3e0199ca2e"] 7
["9bd83b79-186d-4ae5-9373-956dbd515070" 0
"b6172191-fa44-436d-879d-c883e4d240ed" 1
"093b72ba-74cd-48b9-86df-7e7d9341ae53" 2
"88b6c7f8-1d23-4e82-b959-8cb3400cc039" 3
"8279d979-8a57-4595-b9d3-346f6b05924e" 4
"735e6139-0fce-4bb7-a4a2-00ceb86c9b07" 5
"0ad84c4f-e0d8-4606-b563-8b2e32cc632f" 6
"5a86f7ea-0763-4473-ba09-91398e938be7"] 7
["62b2b9c6-1991-48f7-8533-76fa877e9736" 0
"35b56ed8-74f0-42f8-ab1c-ede41605b7bd" 1
"71848241-6348-4fde-935e-74a5c369ede1" 2
"722f05a6-5672-4be6-902d-635372e04758" 3
"b2a45221-aafb-4949-8018-5fed6cf7c7fe" 4
"dbb49783-5f75-4b3c-a793-a933ea321679" 5
"6bb25395-6647-4668-9e6e-158ad5f0b8af" 6
"1b32e613-8e72-420f-b31f-7bc95650386c"] 7
["636e2084-fdeb-4594-a400-10f6ef2791d7" 0
"8ac273ab-b8b2-46af-a8b4-f8fb22afe8e4" 1
"372e4f00-4ce9-4a9f-927b-d34c5a4968c1" 2
"f821abb1-d97e-4d99-b630-f74de5d106c1" 3
"d40b9b64-e81d-4133-bde2-54975806c087" 4
"07937692-680f-4cb0-8d17-98684141b92c" 5
"3b2039d0-de86-4cd7-9fb2-21397932f14c" 6
"16c24542-65c8-45db-97dc-014e66db7ef0"] 7
["f67efbcc-898d-4b50-8c15-21ac4fbbc500" 0
"64c020c7-9bd1-4e00-968f-180e3d68e100" 1
"3667915a-8e10-41fb-8f00-035cc10324a6" 2
"b7bc23c3-f5a1-486c-a99a-6c61357ed000" 3
"11292acd-ef71-4e0c-8281-0f50007cf850" 4
"210cca62-61b4-4ed9-ad42-653a909d3045" 5
"1dd2468a-0a3c-43e6-aae6-bd702d1c8a74" 6
"d7f8e5ee-1e05-42e1-8ff4-89529a210a76"] 7
["a1de7674-fa0b-49e6-af6a-2522798c4861" 0
"5cca7cd7-f50b-4538-ad89-a85b2d72a555" 1
"30cd353c-ee8c-4a94-9fbd-166372c2fd96" 2
"7407ab86-fdf6-4bf1-8282-e1218e021ed3" 3
"20ce7593-b1e2-4401-9b7c-1af18ec37f6c" 4
"541e995a-1416-4f4b-9696-2827cdcbd64e" 5
"3247610e-0486-4891-8fce-32f2e03fcaec" 6
"6492db47-54af-4390-9c88-11f43c3eaef0"]] 7

The numbering needs to start from the beginning after every open and closed parentheses. It's half working as expected but how can I accomplish this?


问:
How to disabled select text and copy in next js?
I'm still new to next javascript, how do I prevent my blog from being copied and pasted?</p>


问:
is there a python pattern that allows an attribute in a base class be an instance of the derived class?
Is there some clever way to do this that works?

```<code>class NamedElement:
    def __init__(self, **kwargs):
       self.name = Property(name=kwargs.get('name')) #you're going to regret this

class Property(NamedElement):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

myprop = Property(name='myprop') #don't hit enter!!!
</code>```

If anyone wants context, I'm interested in trying to build a UML model in Python .. UML models itself with UML so here I am.

Body:
Is there some clever way to do this that works?

class NamedElement:
    def __init__(self, **kwargs):
       self.name = Property(name=kwargs.get('name')) #you're going to regret this

class Property(NamedElement):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

myprop = Property(name='myprop') #don't hit enter!!!

If anyone wants context, I'm interested in trying to build a UML model in Python .. UML models itself with UML so here I am.


问:
Unusual high CPU usage in browser triggered by a style transition
The problem occurs in both Chrome and Firefox, on an up-to-date Ubuntu 20.4 system.

I have a page consisting of nothing but links, and recently added this code to it:

```<code><style>
        a { white-space: nowrap; border-bottom-color: var(--c-highlight); }
</style>

…

anchor.onmousedown = function(b) {
    if (b.button <= 1) {
        this.style.transitionDuration = "0s"
        this.style.borderBottomWidth = ".3em"
    }
}
anchor.onmouseup = function(b) {
    if (b.button <= 1) {
        this.style.transitionDuration="7200s"
        this.style.borderBottomWidth = "0"
    }
}
</code>```

It works fine: the link gets underlined in bright yellow for the next 2 hours, indicating that it's recently been used.

But, after a few clicks, the page starts burning large amounts of CPU (approaching 100%) whenever that page is visible.
The more clicks, the more CPU.

If I disable it (change the "1" to "-1"), the style doesn't change and the CPU is unaffected.

I admit it might be unusual code usage, but why would it have this effect?

Update:

If I add this.style.transitionDelay="7195s" to the mouseup function, and "0s" to mousedown, the problem more or less goes away.

But that's because the actual transition takes only 5 seconds rather than 2 hours, and seldom with more than one instance at the same time.

The question remains though, why would such a simple transition require such massive amounts of CPU?

Body:
The problem occurs in both Chrome and Firefox, on an up-to-date Ubuntu 20.4 system.

I have a page consisting of nothing but links, and recently added this code to it:

…

anchor.onmousedown = function(b) {
    if (b.button <= 1) {
        this.style.transitionDuration = "0s"
        this.style.borderBottomWidth = ".3em"
    }
}
anchor.onmouseup = function(b) {
    if (b.button <= 1) {
        this.style.transitionDuration="7200s"
        this.style.borderBottomWidth = "0"
    }
}

It works fine: the link gets underlined in bright yellow for the next 2 hours, indicating that it's recently been used.

But, after a few clicks, the page starts burning large amounts of CPU (approaching 100%) whenever that page is visible.
The more clicks, the more CPU.

If I disable it (change the "1" to "-1"), the style doesn't change and the CPU is unaffected.

I admit it might be unusual code usage, but why would it have this effect?

Update:

If I add this.style.transitionDelay="7195s" to the mouseup function, and "0s" to mousedown, the problem more or less goes away.

But that's because the actual transition takes only 5 seconds rather than 2 hours, and seldom with more than one instance at the same time.

The question remains though, why would such a simple transition require such massive amounts of CPU?


问:
Spotipy hangs forever when trying to call method on spotipy object
I have the exact same problem as this person: Spotipy getting stuck on queries, no return on all functions that query Spotify

This is how I define the spotipy object:

```<code>client_credentials_manager = SpotifyClientCredentials(client_id=cid, client_secret=secret)
sp = spotipy.Spotify(client_credentials_manager = client_credentials_manager)
</code>```

and something as simple as this hangs and forces me to restart the kernel.

```<code>weeknduri = 'spotify:artist:1Xyo4u8uXC1ZmMpatF05PJ'
results = sp.artist_top_tracks(weeknduri)
results
</code>```

I've already tried refreshing the client secret from the spotify developer dashboard, creating a new account and using new client ID and secret, nothing has worked.

Body:
I have the exact same problem as this person: Spotipy getting stuck on queries, no return on all functions that query Spotify

This is how I define the spotipy object:

client_credentials_manager = SpotifyClientCredentials(client_id=cid, client_secret=secret)
sp = spotipy.Spotify(client_credentials_manager = client_credentials_manager)

and something as simple as this hangs and forces me to restart the kernel.

weeknduri = 'spotify:artist:1Xyo4u8uXC1ZmMpatF05PJ'
results = sp.artist_top_tracks(weeknduri)
results

I've already tried refreshing the client secret from the spotify developer dashboard, creating a new account and using new client ID and secret, nothing has worked.


问:
How to save user input into an array
How to save user input into an array

I have two modules

MODULE director: Allows you to add and remove teachers.
MODULE Informer: Gives information about the teachers available in the school.
All this in an endless loop.

To the code: I have an initial array of teachersForDirector, consisting of 10 teachers. If the user wants to add or remove a teacher, I use the DeletingTeachers, AddingTeachers methods.
The problem is that when I select the "informer" module, the values of the teachersForDirector array are reset to the original.

Code:

```<code>public static List<string> DeletingTeachers(List<string> arrayTeachers)
        {
            int counter = 0;

            Console.WriteLine("which teacher to remove? [index]");

            for (int i = 0; i < arrayTeachers.Count; i++)
            {
                Console.WriteLine($"teacher with number - {counter} {arrayTeachers[i]}");
                counter++;
            }
            int index = int.Parse(Console.ReadLine());
            arrayTeachers.RemoveAt(index);
            Console.Clear();
            for (int i = 0; i < arrayTeachers.Count; i++)
            {
                Console.WriteLine($"new teachers - {arrayTeachers[i]}");
            }
            return arrayTeachers;
        }
        public static List<string> AddingTeachers(List<string> arrayTeachers)
        {

            Console.WriteLine("enter the name of the new teacher");
            arrayTeachers.Add(Console.ReadLine());

            for (int i = 0; i < arrayTeachers.Count; i++)
            {
                Console.WriteLine($"{arrayTeachers[i]}");
            }
            Console.Clear();
            Console.WriteLine("teachers information:");
            for (int i = 0; i < arrayTeachers.Count; i++)
            {
                Console.WriteLine($"{arrayTeachers[i]}");
            }
            return arrayTeachers;
        }

      static void Main(string[] args)
        {
            while (true)
            {
                List<string> teachersForDirector = new List<string> { "Матвеева Н.В", "Ивашина А.С", "Изюмов Р.Н.", "Жиделев А.С.", "Карпов М.Д", "Петрова О.А", "Таран Г.Г.", "Овчарова Д.Е.", "Андреев Д.Е.", "Долгих Н.О." };

                Console.WriteLine("Choose:\ndirector - 0 \ninformer - 1"); // MAIN MENU
                int DirectorZeroInformerOne = int.Parse(Console.ReadLine());
                Console.Clear();
                if (DirectorZeroInformerOne == 0) // changing teachers
                {
                    {

                        Console.WriteLine("вы хотите удалить учителя[1] или добавить нового[2]?");
                        int chooseDeleteOrNew = int.Parse(Console.ReadLine());
                        Console.Clear();
                        if (chooseDeleteOrNew == 1) // removing a teacher
                        {
                            DeletingTeachers(teachersForDirector);
                        }
                        if (chooseDeleteOrNew == 2) // adding a teacher
                        {
                            AddingTeachers(teachersForDirector);
                        }
                    }
                }
                if (DirectorZeroInformerOne == 1)
                {
                    Console.WriteLine("information about teachers");
                    for (int i = 0; i < teachersForDirector.Count; i++)
                    {
                        Console.WriteLine(teachersForDirector[i]);
                    }
                }
            }
        }
</code>```

How do I make sure that the changed data is saved and the informer module outputs the correct information?

Title: How to save user input into an array

Body:
How to save user input into an array

I have two modules

MODULE director: Allows you to add and remove teachers.
MODULE Informer: Gives information about the teachers available in the school.
All this in an endless loop.

To the code: I have an initial array of teachersForDirector, consisting of 10 teachers. If the user wants to add or remove a teacher, I use the DeletingTeachers, AddingTeachers methods.
The problem is that when I select the "informer" module, the values of the teachersForDirector array are reset to the original.

Code:

public static List<string> DeletingTeachers(List<string> arrayTeachers)
        {
            int counter = 0;

            Console.WriteLine("which teacher to remove? [index]");

            for (int i = 0; i < arrayTeachers.Count; i++)
            {
                Console.WriteLine($"teacher with number - {counter} {arrayTeachers[i]}");
                counter++;
            }
            int index = int.Parse(Console.ReadLine());
            arrayTeachers.RemoveAt(index);
            Console.Clear();
            for (int i = 0; i < arrayTeachers.Count; i++)
            {
                Console.WriteLine($"new teachers - {arrayTeachers[i]}");
            }
            return arrayTeachers;
        }
        public static List<string> AddingTeachers(List<string> arrayTeachers)
        {

            Console.WriteLine("enter the name of the new teacher");
            arrayTeachers.Add(Console.ReadLine());

            for (int i = 0; i < arrayTeachers.Count; i++)
            {
                Console.WriteLine($"{arrayTeachers[i]}");
            }
            Console.Clear();
            Console.WriteLine("teachers information:");
            for (int i = 0; i < arrayTeachers.Count; i++)
            {
                Console.WriteLine($"{arrayTeachers[i]}");
            }
            return arrayTeachers;
        }

      static void Main(string[] args)
        {
            while (true)
            {
                List<string> teachersForDirector = new List<string> { "Матвеева Н.В", "Ивашина А.С", "Изюмов Р.Н.", "Жиделев А.С.", "Карпов М.Д", "Петрова О.А", "Таран Г.Г.", "Овчарова Д.Е.", "Андреев Д.Е.", "Долгих Н.О." };

                Console.WriteLine("Choose:\ndirector - 0 \ninformer - 1"); // MAIN MENU
                int DirectorZeroInformerOne = int.Parse(Console.ReadLine());
                Console.Clear();
                if (DirectorZeroInformerOne == 0) // changing teachers
                {
                    {

                        Console.WriteLine("вы хотите удалить учителя[1] или добавить нового[2]?");
                        int chooseDeleteOrNew = int.Parse(Console.ReadLine());
                        Console.Clear();
                        if (chooseDeleteOrNew == 1) // removing a teacher
                        {
                            DeletingTeachers(teachersForDirector);
                        }
                        if (chooseDeleteOrNew == 2) // adding a teacher
                        {
                            AddingTeachers(teachersForDirector);
                        }
                    }
                }
                if (DirectorZeroInformerOne == 1)
                {
                    Console.WriteLine("information about teachers");
                    for (int i = 0; i < teachersForDirector.Count; i++)
                    {
                        Console.WriteLine(teachersForDirector[i]);
                    }
                }
            }
        }

How do I make sure that the changed data is saved and the informer module outputs the correct information?


问:
Primeng Calendar inside dialog problem depending on the body scroll
I've tried many different approaches, as to set z-index, overflow to visibile and appendTo to the dialog itself, however, the dialog will cutoff if I am the bottom of the page using appendToBody

Here is the stackblitz to reproduce it
https://stackblitz.com/edit/primeng-calendar-demo-3mxxnt?file=src/app/app.component.html

Note: you need to not have enough vertical height to reproduce it.

How do I solve this to never cut off?


问:
Difference between Locator.filter and Locator.locator?
What's the difference between Locator.filterand Locator.locator? Seems to me both can be used interchangeably? How do they effectively differ?


问:
React nested items rerender not working as expected
im trying to develop component that will sort new items, depending if item parent is or is not present on the list already. Components can be nested in each other to unlimited depth. Parent have list of children, children have parentId. Now, it works as expected at the first render, but when new item appear on the list (its added by user, using form, up in the structure), it does in fact make its way to components list, but is not shown on the screen until page reload. I can see temporary list that is used to make all calculations have the item as expected in the nested structure. Then i set state list to value of temp, but its not working, and i dont know why. Im quite new to react stuff. In act of desperation i even tried to destructure root parent of the item, hoping it will force rerender, but that didnt worked too. Anybody could help with this?

http://jsfiddle.net/zkfj03um/13/

```<code>import React, { useState } from 'react';

function Component(props) {
    const [component, setComponent] = useState(props.component);
    return (
        <div>
            {component.id};
            {component.name};
            <ul>
                {component.subcomps && component.subcomps.map((comp) =>
                    <li key={comp.id} style={{ textAlign: 'left' }}>
                        <Component component={comp}
                            id={comp.id}
                            name={comp.name}
                            parentId={comp.parentId}
                            subcomps={comp.subcomps}
                        />
                   </li>)}
            </ul>
        </div>
    );
}

function ComponentsList(props) {
    const newComponents = props.newComponents;
    const [filteredComponents, setFilteredComponents] = useState();

    function deepSearch(collection, key, value, path=[]) {
        for (const o of collection) {
          for (const [k, v] of Object.entries(o)) {
            if (k === key && v === value) {
              return {path: path.concat(o), object: o};
            }
            if (Array.isArray(v)) {
              const _o = deepSearch(v, key, value, path.concat(o));
              if (_o) {
                return _o;
              }
            }
          }
        }
      }

    async function filter() {
        let temp = [];
        await newComponents.forEach((comp) => {
            //parent may be, or may not be on the list. Its not necesary
            const parentTuple = deepSearch(filteredComponents, 'id', comp.parentId);
            if (!parentTuple) {
                //create parent substitute logic
            } else {
                const parent = parentTuple.object;
                const root = parentTuple.path[0];
                const mutReplies = [comm, ...parent.replies];
                parent.replies = mutReplies;
                temp = [{...root}, ...temp]
            }
        })
        setFilteredComponents([...temp])
    }

    useEffect(() => {
        setLoading(false);
      }, [filteredComponents]);

      useEffect(() => {
        setLoading(true);
        filter();
      }, [newComponents]);

    return (<>
        {!loading && filteredComponents.map((component, index) =>
            <li key={index}>
                <Component component={component} />
            </li>
        )}
    </>);
}

const items = [
    { id: 1, name: 'sample1', subcomps: [{ id: 5, name: 'subcomp1', parentId: 1, subcomps: [] }] },
    {
        id: 2, name: 'sample2', subcomps: [
            { id: 6, name: 'subcomp2', subcomps: [], parentId: 2 },
            { id: 7, name: 'subcomp3', subcomps: [], parentId: 2 }
        ]
    },

]
ReactDOM.render(<ComponentsList newComponents={items} />, document.querySelector("#app"))
</code>```

Body:
im trying to develop component that will sort new items, depending if item parent is or is not present on the list already. Components can be nested in each other to unlimited depth. Parent have list of children, children have parentId. Now, it works as expected at the first render, but when new item appear on the list (its added by user, using form, up in the structure), it does in fact make its way to components list, but is not shown on the screen until page reload. I can see temporary list that is used to make all calculations have the item as expected in the nested structure. Then i set state list to value of temp, but its not working, and i dont know why. Im quite new to react stuff. In act of desperation i even tried to destructure root parent of the item, hoping it will force rerender, but that didnt worked too. Anybody could help with this?

http://jsfiddle.net/zkfj03um/13/

import React, { useState } from 'react';

function Component(props) {
    const [component, setComponent] = useState(props.component);
    return (

            {component.id};
            {component.name};

                {component.subcomps && component.subcomps.map((comp) =>

                        <Component component={comp}
                            id={comp.id}
                            name={comp.name}
                            parentId={comp.parentId}
                            subcomps={comp.subcomps}
                        />

)}

    );
}

function ComponentsList(props) {
    const newComponents = props.newComponents;
    const [filteredComponents, setFilteredComponents] = useState();

    function deepSearch(collection, key, value, path=[]) {
        for (const o of collection) {
          for (const [k, v] of Object.entries(o)) {
            if (k === key && v === value) {
              return {path: path.concat(o), object: o};
            }
            if (Array.isArray(v)) {
              const _o = deepSearch(v, key, value, path.concat(o));
              if (_o) {
                return _o;
              }
            }
          }
        }
      }

    async function filter() {
        let temp = [];
        await newComponents.forEach((comp) => {
            //parent may be, or may not be on the list. Its not necesary
            const parentTuple = deepSearch(filteredComponents, 'id', comp.parentId);
            if (!parentTuple) {
                //create parent substitute logic
            } else {
                const parent = parentTuple.object;
                const root = parentTuple.path[0];
                const mutReplies = [comm, ...parent.replies];
                parent.replies = mutReplies;
                temp = [{...root}, ...temp]
            }
        })
        setFilteredComponents([...temp])
    }

    useEffect(() => {
        setLoading(false);
      }, [filteredComponents]);

      useEffect(() => {
        setLoading(true);
        filter();
      }, [newComponents]);

    return (<>
        {!loading && filteredComponents.map((component, index) =>

                <Component component={component} />

        )}
    </>);
}

const items = [
    { id: 1, name: 'sample1', subcomps: [{ id: 5, name: 'subcomp1', parentId: 1, subcomps: [] }] },
    {
        id: 2, name: 'sample2', subcomps: [
            { id: 6, name: 'subcomp2', subcomps: [], parentId: 2 },
            { id: 7, name: 'subcomp3', subcomps: [], parentId: 2 }
        ]
    },

]
ReactDOM.render(<ComponentsList newComponents={items} />, document.querySelector("#app"))


问:
Graphviz Binary Search Tree
quick question, is there a way to display a tree is more bst manner, instead of standard graph one?

Title: Graphviz Binary Search Tree