eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: I'm trying to remove the top and right spine of a plot, and initially tried # Create a figure and axis with PlateCarree projection fig, ax = plt.subplots(figsize=(11, 6), subplot_kw={'projection': ccrs.PlateCarree()}) ax.coastlines() # Reintroduce spines ax.spines['top'].set_visible(True) ax.spines['right'].set_visible(True) ax.set_xticks(range(-180, 181, 30), crs=ccrs.PlateCarree()) ax.set_yticks(range(-90, 91, 30), crs=ccrs.PlateCarree()) # Show the plot plt.show()  which gives me this figure, i.e. it clearly didn't work  I then tried to remove the frame and add the two spines I want # Create a figure and axis with PlateCarree projection fig, ax = plt.subplots(figsize=(11, 6), subplot_kw={'projection': ccrs.PlateCarree(), 'frameon': False}) ax.coastlines() # Reintroduce spines ax.spines['left'].set_visible(True) ax.spines['bottom'].set_visible(True) ax.set_xticks(range(-180, 181, 30), crs=ccrs.PlateCarree()) ax.set_yticks(range(-90, 91, 30), crs=ccrs.PlateCarree()) # Show the plot plt.show()  and this also doesn't quite work - I successfully remove the frame but can't reintroduce the left and bottom spine back  I did see this post but when I try to apply this to my code # Create a figure and axis with PlateCarree projection fig, ax = plt.subplots(figsize=(11, 6), subplot_kw={'projection': ccrs.PlateCarree()}) ax.coastlines() # Reintroduce spines ax.outline_patch.set_visible(False) ax.spines['left'].set_visible(True) ax.spines['bottom'].set_visible(True) ax.set_xticks(range(-180, 181, 30), crs=ccrs.PlateCarree()) ax.set_yticks(range(-90, 91, 30), crs=ccrs.PlateCarree()) # Show the plot plt.show()  I get the error AttributeError: 'GeoAxes' object has no attribute 'outline_patch'  Surely there must be a way to achieve this? Does anyone know how to do this? I'm using python 3.10.

Answer: I think the modern equivalent of outline_patch is spines['geo']: # Create a figure and axis with PlateCarree projection fig, ax = plt.subplots(figsize=(11, 6), subplot_kw={'projection': ccrs.PlateCarree()}) ax.coastlines() ax.spines['geo'].set_visible(False) ax.spines['left'].set_visible(True) ax.spines['bottom'].set_visible(True) ax.set_xticks(range(-180, 181, 30), crs=ccrs.PlateCarree()) ax.set_yticks(range(-90, 91, 30), crs=ccrs.PlateCarree()) # Show the plot plt.show()
Question: Let's say I want a last specific value from the CSV file. THis is my code. When I run this code, it gives me the value saying "2 Ana" What can I do here to just get the value 'Ana'? import pandas as pd import csv CSV_file = pd.read_csv('appl.csv') name = CSV_file['Name'] v_val = name.iloc[-1:] print(v_val)  THe CSV file is this: Name,Age,Location Juan,18,Lisbon James,19,London Ana,20,Madrid  I want to get the value 'Ana'

Answer: Remove the : from the .iloc: name = CSV_file["Name"].iloc[-1] print(name)  Prints: Ana   Or use .iat: name = CSV_file["Name"].iat[-1]
Question: I'm working with Python 3.11. I have a dictionary whose keys are datetime objects and whose values are strings. dates = {datetime.datetime(2022, 1, 1): "a", datetime.datetime(2022, 5, 4): "b", datetime.datetime(2022, 9, 25): "c", datetime.datetime(2023, 5, 17): "d", datetime.datetime(2023, 12, 15): "e", datetime.datetime(2024, 3, 17): "f", datetime.datetime(2024, 4, 3): "g"}  I would like to know if there is a way to remove all the elements that have already passed (other than iterating through all the elements). For example in this case datetime.datetime.now() = datetime.datetime(2024, 2, 9) so the result dictionary will be: dates = {datetime.datetime(2024, 3, 17): "f", datetime.datetime(2024, 4, 3): "g"}  This code works in case the dictionary is ordered by date (which may not be the case): new_dates = {} now = datetime.datetime.now() for k, v in reversed(dates.items()): if k < now: break new_dates[k] = v  But I would like to know if there is any other way without a loop or thay might work in a disorderly dictionary.

Answer: You could form a new Dictionary using a comprehension; order does not matter: dates2 = {k:v for k, v in dates.items() if k > now}  which gives {datetime.datetime(2024, 3, 17, 0, 0): 'f', datetime.datetime(2024, 4, 3, 0, 0): 'g'}
Question: I have array of length n, from which I build such sequence b that: b[0] = 0 b[1] = b[0] + a[0] b[2] = b[1] + a[0] b[3] = b[2] + a[1] b[4] = b[3] + a[0] b[5] = b[4] + a[1] b[6] = b[5] + a[2] b[7] = b[6] + a[0] b[8] = b[7] + a[1] b[9] = b[8] + a[2] b[10] = b[9] + a[3] #etc.  a can contain non-positive values. I need to find max element of b. I only came up with O(n^2) solution. Is there faster approach? def find_max(a): b = [0] i = 0 count = 0 while i < len(a): j = 0 while j <= i: b.append(b[count] + a[j]) count += 1 j += 1 i += 1 return max(b) 

Answer: O(n) time and O(1) space. Consider this (outer loop) round: b[4] = b[3] + a[0] = b[3] + a[0] b[5] = b[4] + a[1] = b[3] + a[0] + a[1] b[6] = b[5] + a[2] = b[3] + a[0] + a[1] + a[2]  You don't need all of these. It's enough to know:  The maximum of them. Which is b[3] + max(prefix sums of a[:3]). The last of them, b[6] = b[3] + sum(a[:3]). Because you need that for the next round.  In general, to find the maximum of each round, it's enough to know:  The b value which the round starts with. The max prefix sum of a[:...].  Add them together to know the max b-value in the round. And return the maximum of these rounds maximums. We can update these values in O(1) time for each round: def find_max_linear(a): b = max_b = 0 sum_a = max_sum_a = 0 for x in a: sum_a += x max_sum_a = max(max_sum_a, sum_a) max_b = max(max_b, b + max_sum_a) b += sum_a return max_b  Testing: import random for _ in range(10): a = random.choices(range(-100, 101), k=100) expect = find_max(a) result = find_max_linear(a) print(result == expect, expect, result)  Output (Attempt This Online!): True 8277 8277 True 2285 2285 True 5061 5061 True 19261 19261 True 0 0 True 0 0 True 47045 47045 True 531 531 True 703 703 True 24073 24073  Fun oneliner (also O(n) time, but O(n) space due to the unpacking): from itertools import accumulate as acc from operator import add def find_max_linear(a): return max(0, *map(add, acc(acc(a), initial=0), acc(acc(a), max)))  Or broken into a few lines with comments: def find_max_linear(a): return max(0, *map( add, acc(acc(a), initial=0), # each round's initial b-value acc(acc(a), max) # each round's max prefix sum of a[:...] ))  Attempt This Online!
Question: I read here the following: "The Python stdlib module random contains pseudo-random number generator with a number of methods that are similar to the ones available in Generator." However, the first link for a Python module "random" has a URL that points to Numpy's random.random documentation, not to some general Python library. Is this link wrong or am I just not getting what the documentation is trying to say here? I'm quite confused by all the different options to generate random numbers in Python. I count at least four now:  numPy singleton RandomState object  numPy RandomState object  numPy Generator object  Python's general random functionality apparently.   Any insight is much welcome.

Answer:  Is this link wrong?  Yes. In context, I think they mean this random. There are three pieces of evidence for this.  It says it's in the stdlib, and NumPy is not in the stdlib. It is an optional library for Python.  It's talking about a module, and np.random.random() is not a module - it's a function inside a module.  Later, in the same paragraph, it says:  The Python stdlib module random contains pseudo-random number generator with a number of methods that are similar to the ones available in Generator. It uses Mersenne Twister, and this bit generator can be accessed using MT19937. Generator, besides being NumPy-aware, has the advantage that it provides a much larger number of probability distributions to choose from.  It makes no sense to say that np.random.random() is not NumPy-aware - it's part of NumPy. On the other hand, it does make sense to describe the stdlib random module as not being NumPy-aware. The stdlib random module cannot create a NumPy array of random numbers. It's intended to work even if you don't have NumPy installed.
Question: I need to write the following function:  Write a function that takes in a target (int) and a list of ints. The function should return a list of any combination of elements that add up to the target, if there is no combination that adds up to target return None.  This is my initial solution using recursion: def how_sum(target: int, nums: list[int]) -> list[int] | None: if target == 0: return [] if target < 0: return None for num in nums: remainder = target - num rv = how_sum(remainder, nums) if rv is not None: return rv + [num] return None  Then I tried to reduce the time complexity and make my code efficient even for large numbers: def how_sum(target: int, nums: list[int], memo: dict[int, list[int]] = {}) -> list[int] | None: if target in memo: return memo[target] if target == 0: return [] if target < 0: return None for num in nums: remainder = target - num rv = how_sum(remainder, nums, memo) if rv is not None: memo[target] = rv + [num] # Note: if I comment this line everything works fine! return rv + [num] memo[target] = None return None def main(): print(how_sum(7, [2, 3])) # [3, 2, 2] print(how_sum(7, [5, 3, 4, 7])) # [3, 2, 2] print(how_sum(7, [2, 4])) # [3, 2, 2] print(how_sum(8, [2, 3, 5])) # [2, 2, 2, 2] print(how_sum(500, [7, 14])) # [3, 7, 7, 7, 7, 7, ..., 7] main()  As you can see in the comments it returns the wrong output. These are the correct output: def main(): print(how_sum(7, [2, 3])) # [3, 2, 2] print(how_sum(7, [5, 3, 4, 7])) # [4, 3] print(how_sum(7, [2, 4])) # None print(how_sum(8, [2, 3, 5])) # None print(how_sum(500, [7, 14])) # None  When I comment this line memo[target] = rv + [num] everything works fine but I can't figure out why it doesn't work if I leave it as it is.

Answer: There are two issues I see with this code. First your claim about the correct solution to this input: print(how_sum(8, [2, 3, 5])) # None  seems incorrect. Given the explanation, either [3, 5] or [2, 2, 2, 2] are valid answers. Similarly for:  print(how_sum(7, [5, 3, 4, 7])) # [4, 3]  where [7] is also a valid result. As far as your code issue, the problem is a common one in that you're using a dangerous default value in a situation where it isn't warranted: def how_sum(target, nums, memo={})  Since nums is different between top level calls, the memo cache has to be reinitialized at the start of each recursion stack. Otherwise, you have results in it from a previous run where nums was different. One possible approach: def how_sum(target: int, nums: list[int], memo: dict[int, list[int]] = None) -> list[int] | None: if memo is None: memo = {0: []} if target not in memo: memo[target] = None if target > 0: for num in nums: remainder = target - num rv = how_sum(remainder, nums, memo) if rv is not None: memo[target] = [*rv, num] break return memo[target]
Question: I came across this integral approximation function in a book. It seems efficient and provides accurate results with fewer subintervals ((n)). def approximate_integral(a, b, n, f): delta_x = (b - a) / n total_sum = 0 for i in range(1, n + 1): midpoint = 0.5 * (2 * a + delta_x * (2 * i - 1)) total_sum += f(midpoint) return total_sum * delta_x  Since the above midpoint calculation isn't obvious, I searched for the mathematical formula and implemented it. However, it approaches the correct answer only when I use far more intervals than the implementation found in the book. midpoint = a + 2 * dx + i * dx  def approximate_integral(a, b, n, f): dx = (b - a) / n tot_sum = 0 for i in range(1, n + 1): midpoint = a + (dx / 2) + (i * dx) tot_sum += f(midpoint) return tot_sum * dx  Please explain the efficiency and the differences between this formula and the one I used: midpoint = 0.5 * (2 * a + delta_x * (2 * i - 1)) 

Answer: I found that the midpoint in my function accounted for an extra interval. After I reduced the ith iteration by 1, it worked as the formula in the book. midpoint = a + (dx/2) + ((i-1) * dx)
Question: I trained two different type of ResNet model from torchvision.models which is ResNet50 with DEFAULT weight and ResNet101 with DEFAULT weight too but the results of training is really weird, the train accuracy and test accuracy of ResNet50 model is 89 and 85 respectively and for ResNet101 is 34, 28 ! what is wrong? I froze the entire models and just trained the FC layer which is modified to have 4 output(equals to length of the classes) I used 5 epochs for both. why ResNet101 is worse than ResNet50?? shouldn't this be better? because has more layers(depth)

Answer:  shouldn't this be better? because has more layers(depth)  More layers means the model is more complex and has more capacity, but that doesn't mean it will perform better. Deeper models can struggle to converge, resulting in both a lower train and validation score compared to a simpler one. I think this is what's happening in your case. Try training the larger model for more epochs and with a different learning rate. More epochs give the model more time to adapt. I'd start with a smaller learning rate, and see how the model responds to larger rates. Change one thing at a time and observe its effect. If it converges fine, it can still go too far and overfit, which means it'll score highly on the training set but less well on the validation set compared to a simpler model. This will be exacerbated if the dataset is relatively small and non-diverse.
Question: When I try to run az bicep version I'm getting this error The command failed with an unexpected error. Here is the traceback: [WinError 193] %1 is not a valid Win32 application Traceback (most recent call last): File "D:\a\_work\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\knack/cli.py", line 233, in invoke File "D:\a\_work\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/cli/core/commands/__init__.py", line 664, in execute File "D:\a\_work\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/cli/core/commands/__init__.py", line 729, in _run_jobs_serially File "D:\a\_work\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/cli/core/commands/__init__.py", line 698, in _run_job File "D:\a\_work\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/cli/core/commands/__init__.py", line 334, in __call__ File "D:\a\_work\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/cli/core/commands/command_operation.py", line 121, in handler File "D:\a\_work\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/cli/command_modules/resource/custom.py", line 4601, in show_bicep_cli_version File "D:\a\_work\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/cli/command_modules/resource/_bicep.py", line 94, in run_bicep_command File "D:\a\_work\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/cli/command_modules/resource/_bicep.py", line 267, in _get_bicep_installed_version File "D:\a\_work\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure/cli/command_modules/resource/_bicep.py", line 305, in _run_command File "subprocess.py", line 548, in run File "subprocess.py", line 1026, in __init__ File "subprocess.py", line 1538, in _execute_child OSError: [WinError 193] %1 is not a valid Win32 application  And the same error I have running all az bicep *** commands. I tried to reinstall azure cli. Did not help. I deleted py related paths from PATH env variables. That was a suggestion from some github issue page.

Answer: The most likely cause of your error is that the bicep executable installed by Azure CLI is corrupted. See Issue #2364 on their repository. As described in this comment you can clean up the %USERPROFILE\.azure\bin directory and run az bicep install to get it working.
Question: Example: I have the following Gradio UI: import gradio as gr def dummy(a): return 'hello', {'hell': 'o'} with gr.Blocks() as demo: txt = gr.Textbox(value="test", label="Query", lines=1) answer = gr.Textbox(value="", label="Answer") answerjson = gr.JSON() btn = gr.Button(value="Submit") btn.click(dummy, inputs=[txt], outputs=[answer, answerjson]) gr.ClearButton([answer, answerjson]) demo.launch()   How can I change the code so that the "Submit" and "Clear" buttons are shown between the answer and JSON boxes, i.e.:  I can't just move the line gr.ClearButton([answer, answerjson]) before answerjson = gr.JSON(), since answerjson needs to be defined in gr.ClearButton([answer, answerjson]).

Answer: You can add the components of clear button after initialization. This way, you are able to decouple the component creation order: import gradio as gr def dummy(a): return "hello", {"hell": "o"} with gr.Blocks() as demo: txt = gr.Textbox(value="test", label="Query", lines=1) answer = gr.Textbox(value="", label="Answer") btn = gr.Button(value="Submit") clear_btn = gr.ClearButton() answerjson = gr.JSON() btn.click(dummy, inputs=[txt], outputs=[answer, answerjson]) clear_btn.add([answer, answerjson]) demo.launch(share=True)
Question: Previous to Polars version 0.20.7, the pivot() method, if given multiple values for the columns argument, would apply the aggregation logic against each column in columns individually based on the index column, rather than against a collective set of columns. Before: df = pl.DataFrame( { "foo": ["one", "one", "two", "two", "one", "two"], "bar": ["y", "y", "y", "x", "x", "x"], "biz": ['m', 'f', 'm', 'f', 'm', 'f'], "baz": [1, 2, 3, 4, 5, 6], } ) df.pivot(index='foo', values='baz', columns=('bar', 'biz'), aggregate_function='sum')  returns: shape: (2, 5) ┌─────┬─────┬─────┬─────┬─────┐ │ foo ┆ y ┆ x ┆ m ┆ f │ │ --- ┆ --- ┆ --- ┆ --- ┆ --- │ │ str ┆ i64 ┆ i64 ┆ i64 ┆ i64 │ ╞═════╪═════╪═════╪═════╪═════╡ │ one ┆ 3 ┆ 5 ┆ 6 ┆ 2 │ │ two ┆ 3 ┆ 10 ┆ 3 ┆ 10 │ └─────┴─────┴─────┴─────┴─────┘  After (in 0.20.7): shape: (2, 5) ┌─────┬───────────┬───────────┬───────────┬───────────┐ │ foo ┆ {"y","m"} ┆ {"y","f"} ┆ {"x","f"} ┆ {"x","m"} │ │ --- ┆ --- ┆ --- ┆ --- ┆ --- │ │ str ┆ i64 ┆ i64 ┆ i64 ┆ i64 │ ╞═════╪═══════════╪═══════════╪═══════════╪═══════════╡ │ one ┆ 1 ┆ 2 ┆ null ┆ 5 │ │ two ┆ 3 ┆ null ┆ 10 ┆ null │ └─────┴───────────┴───────────┴───────────┴───────────┘  I like the previous functionality much better; it's very awkward to deal with the new pivoted table, especially given its column names. Polars devs put this change under "Bug fixes" but it actually broke my code.

Answer: I see a couple of ways you could do it: First, you can use melt() for your DataFrame first and then pivot: df.melt(["foo", "baz"]) ─────┬─────┬──────────┬───────┐ │ foo ┆ baz ┆ variable ┆ value │ │ --- ┆ --- ┆ --- ┆ --- │ │ str ┆ i64 ┆ str ┆ str │ ╞═════╪═════╪══════════╪═══════╡ │ one ┆ 1 ┆ bar ┆ y │ │ one ┆ 2 ┆ bar ┆ y │ │ two ┆ 3 ┆ bar ┆ y │ │ two ┆ 4 ┆ bar ┆ x │ │ one ┆ 5 ┆ bar ┆ x │ │ … ┆ … ┆ … ┆ … │ │ one ┆ 2 ┆ biz ┆ f │ │ two ┆ 3 ┆ biz ┆ m │ │ two ┆ 4 ┆ biz ┆ f │ │ one ┆ 5 ┆ biz ┆ m │ │ two ┆ 6 ┆ biz ┆ f │ └─────┴─────┴──────────┴───────┘  and then pivot the same way: ( df .melt(["foo", "baz"]) .pivot(index='foo', values='baz', columns='value', aggregate_function='sum') ) ┌─────┬─────┬─────┬─────┬─────┐ │ foo ┆ y ┆ x ┆ m ┆ f │ │ --- ┆ --- ┆ --- ┆ --- ┆ --- │ │ str ┆ i64 ┆ i64 ┆ i64 ┆ i64 │ ╞═════╪═════╪═════╪═════╪═════╡ │ one ┆ 3 ┆ 5 ┆ 6 ┆ 2 │ │ two ┆ 3 ┆ 10 ┆ 3 ┆ 10 │ └─────┴─────┴─────┴─────┴─────┘  Alternatively, if lists of possible values are not intersecting between columns you need to aggregate, you could use concat() with how = align: pl.concat( [df.pivot(index='foo', values='baz', columns=col, aggregate_function="sum") for col in ['bar','biz']], how='align' ) ┌─────┬─────┬─────┬─────┬─────┐ │ foo ┆ y ┆ x ┆ m ┆ f │ │ --- ┆ --- ┆ --- ┆ --- ┆ --- │ │ str ┆ i64 ┆ i64 ┆ i64 ┆ i64 │ ╞═════╪═════╪═════╪═════╪═════╡ │ one ┆ 3 ┆ 5 ┆ 6 ┆ 2 │ │ two ┆ 3 ┆ 10 ┆ 3 ┆ 10 │ └─────┴─────┴─────┴─────┴─────┘
Question: Want to remove "This CKEditor 4.22.1 version is not secure. Consider upgrading to the latest one, 4.24.0-lts." from appearing in my Django admin's RichTextUploadingField. Currently using Django CKEditor 6.7.0m all settings are in settings.py only. Configs: CKEDITOR_CONFIGS = { "default": { "skin": "moono", "toolbar": "Custom", "allowedContent": True, "extraAllowedContent": "object\[id,name,width,height\];", "extraPlugins": "iframe", "iframe_attributes": { "sandbox": "allow-scripts allow-same-origin allow-popups allow-presentation allow-forms", "allowfullscreen": "", "loading": "lazy", "referrerpolicy": "no-referrer-when-downgrade", }, "toolbar_Custom": \[ { "name": "document", "items": \[ "Source", "-", "Save", "NewPage", "Preview", "Print", "-", "Templates", \], }, { "name": "clipboard", "items": \[ "Cut", "Copy", "Paste", "PasteText", "PasteFromWord", "-", "Undo", "Redo", \], }, {"name": "editing", "items": \["Find", "Replace", "-", "SelectAll"\]}, { "name": "forms", "items": \[ "Form", "Checkbox", "Radio", "TextField", "Textarea", "Select", "Button", "ImageButton", "HiddenField", \], }, "/", { "name": "basicstyles", "items": \[ "Bold", "Italic", "Underline", "Strike", "Subscript", "Superscript", "-", "RemoveFormat", \], }, { "name": "paragraph", "items": \[ "NumberedList", "BulletedList", "-", "Outdent", "Indent", "-", "Blockquote", "CreateDiv", "-", "JustifyLeft", "JustifyCenter", "JustifyRight", "JustifyBlock", "-", "BidiLtr", "BidiRtl", "Language", \], }, {"name": "links", "items": \["Link", "Unlink", "Anchor"\]}, { "name": "insert", "items": \[ "Image", "Flash", "Table", "HorizontalRule", "Smiley", "SpecialChar", "PageBreak", "Iframe", "Embed", \], }, "/", { "name": "styles", "items": \["Styles", "Format", "Font", "FontSize"\], }, {"name": "colors", "items": \["TextColor", "BGColor"\]}, {"name": "tools", "items": \["Maximize", "ShowBlocks"\]}, { "name": "about", "items": \[ "About", \], }, \], "language": "en", } }  Tried to add "ignoreUpdates": True,"updateCheck": False, to config, but no effect. "CKEDITOR_UPDATE_NOTIFICATION = False" gives nothing too.

Answer: apparently the check of the version of the editor is a new configuration option, described here Class Config (CKEDITOR.config) | CKEditor 4 API docs 2 . It was added in CKEditor version 4.22.0; XWiki upgraded to CKEditor 4.22.1 in this ticket Loading... 4 . From what I tested and from what I understand from the ckeditor configuration, the check itself can be disabled by adding: config.versionCheck = false; in the CKEditor configuration in XWiki in the administration in the advanced section of the editor configuration: https://extensions.xwiki.org/xwiki/bin/view/Extension/CKEditor%20Integration/#HAdministrationSection 7 . This will disable the warning because it will prevent the editor from checking its own version, but it will not fix the version of the editor in any way. Hope this helps, Anca https://forum.xwiki.org/t/cke-editor-warning-4-22-1-version-not-secure/14020/4