eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: If I have a list of posts, which have created and updated dates with a default attached onupdate callback. Sometimes I need to flag the post, for inappropriate reports or similar actions. I do not want the created and updated dates to be modified. How can I skip the defined onupdate, while making an update action?

Answer: SQLAlchemy will apply a default when  no value was provided to the INSERT or UPDATE statement for that column  however the obvious workaround - explicitly setting the column to its current value - won't work because the session checks whether the value has actually changed, and does not pass a value if it hasn't. Here are two possible solutions, assuming SQLAlchemy 1.4+ and this model: class Post(db.Model): flag = db.Column(db.Boolean, default=False) last_updated = db.Column(db.DateTime, default=some_func, onupdate=some_func)  Use an event listener Add a before update listener that detects when the flag column is being modified, and mark the timestamp column as modified, even though its value is unchanged. This will make SQLAlchemy add the current value to the update, and so the onupdate function will not be called. import sqlalchemy as sa ... @sa.event.listens_for(Post, 'before_update') def receive_before_update(mapper, connection, target): insp = sa.inspect(target) flag_changed, _, _ = insp.attrs.flag.history if flag_changed: orm.attributes.flag_modified(target, 'last_updated')  Use SQLAlchemy core instead of the ORM SQLAlchemy core doesn't need a session, so the current timestamp value can be passed to an update to avoid triggering the onupdate function. The ORM will be unaware of any changes made in this way, so if done within the context of a session affected objects should be refreshed or expired. This is a "quick and dirty" solution, but might be good enough if flagging happens outside of the normal application flow. with db.engine.begin() as conn: posts = Post.__table__ update = sa.update(posts).where(...).values(flag=True, last_updated=posts.c.last_updated) conn.execute(update)
Question: Screenshot of the error After installing nltk using pip3 install nltk I am unable to import nltk in python shell in macOS  File "<stdin>", line 1, in <module> File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/nltk/__init__.py", line 137, in <module> from nltk.text import * File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/nltk/text.py", line 29, in <module> from nltk.tokenize import sent_tokenize File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/nltk/tokenize/__init__.py", line 65, in <module> from nltk.tokenize.casual import TweetTokenizer, casual_tokenize File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/nltk/tokenize/casual.py", line 49, in <module> import regex # https://github.com/nltk/nltk/issues/2409 File "/Users/userId/Library/Python/3.9/lib/python/site-packages/regex/__init__.py", line 1, in <module> from .regex import * File "/Users/userId/Library/Python/3.9/lib/python/site-packages/regex/regex.py", line 419, in <module> import regex._regex_core as _regex_core File "/Users/userId/Library/Python/3.9/lib/python/site-packages/regex/_regex_core.py", line 21, in <module> import regex._regex as _regex ImportError: dlopen(/Users/userId/Library/Python/3.9/lib/python/site-packages/regex/_regex.cpython-39-darwin.so, 2): no suitable image found. Did find: /Users/userId/Library/Python/3.9/lib/python/site-packages/regex/_regex.cpython-39-darwin.so: code signature in (/Users/userId/Library/Python/3.9/lib/python/site-packages/regex/_regex.cpython-39-darwin.so) not valid for use in process using Library Validation: Trying to load an unsigned library``` 

Answer: Just ran into this, I found that the following fixes it: xcrun codesign --sign - "[YOUR_PATH_TO_DYLIB_HERE]"  In my case the error was like so: ImportError: dlopen(/Users/USER/dev/cr-likes/venv/lib/python3.9/site-packages/regex/_regex.cpython-39-darwin.so, 2): no suitable image found. Did find: /Users/USER/dev/cr-likes/venv/lib/python3.9/site-packages/regex/_regex.cpython-39-darwin.so: code signature in (/Users/USER/dev/cr-likes/venv/lib/python3.9/site-packages/regex/_regex.cpython-39-darwin.so) not valid for use in process using Library Validation: Trying to load an unsigned library  By running xcrun on the shared object, in this case /Users/USER/dev/cr-likes/venv/lib/python3.9/site-packages/regex/_regex.cpython-39-darwin.so the error is now gone.
Question: I want to iterate over pairs of integers in order of the sum of their absolute values. The list should look like: (0,0) (-1,0) (0,1) (0,-1) (1,0) (-2,0) (-1,1) (-1,-1) (0,2) (0,-2) (1,1) (1,-1) (2,0) [...]  For pairs with the same sum of absolute values I don't mind which order they come in. Ideally I would like to be able to create the pairs forever so that I can use each one in turn. How can you do that? For a fixed range I can make the list of pairs in an ugly way with: sorted([(x,y)for x in range(-20,21)for y in range(-20,21)if abs(x)+abs(y)<21],key=lambda x:sum(map(abs,x))  This doesn't allow me to iterate forever and it also doesn't give me one pair at a time.

Answer: This seems to do the trick: from itertools import count # Creates infinite iterator def abs_value_pairs(): for absval in count(): # Generate all possible sums of absolute values for a in range(-absval, absval + 1): # Generate all possible first values b = abs(a) - absval # Compute matching second value (arbitrarily do negative first) yield a, b if b: # If first b is zero, don't output again, otherwise, output positive b yield a, -b  This runs forever, and operates efficiently (avoiding recomputing anything unnecessarily).
Question: Yesterday I came across the new 3Blue1Brown video about Newton's fractal and I was really mesmerized by his live representation of the fractal. (Here's the video link for anybody interested, it's at 13:40: https://www.youtube.com/watch?v=-RdOwhmqP5s) I wanted to have a go at it myself and tried to code it in python (I think he uses python too). I spent a few hours trying to improve my naive implementation and got to a point where I just don't know how could I make it faster. The code looks like this: import os import numpy as np import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec from time import time def print_fractal(state): fig = plt.figure(figsize=(8, 8)) gs = GridSpec(1, 1) axs = [fig.add_subplot(gs[0, 0])] fig.tight_layout(pad=5) axs[0].matshow(state) axs[0].set_xticks([]) axs[0].set_yticks([]) plt.show() plt.close() def get_function_value(z): return z**5 + z**2 - z + 1 def get_function_derivative_value(z): return 5*z**4 + 2*z - 1 def check_distance(state, roots): roots2 = np.zeros((roots.shape[0], state.shape[0], state.shape[1]), dtype=complex) for r in range(roots.shape[0]): roots2[r] = np.full((state.shape[0], state.shape[1]), roots[r]) dist_2 = np.abs((roots2 - state)) original_state = np.argmin(dist_2, axis=0) + 1 return original_state def static(): time_start = time() s = 4 c = [0, 0] n = 800 polynomial = [1, 0, 0, 1, -1, 1] roots = np.roots(polynomial) state = np.transpose((np.linspace(c[0] - s/2, c[0] + s/2, n)[:, None] + 1j*np.linspace(c[1] - s/2, c[1] + s/2, n))) n_steps = 15 time_setup = time() for _ in range(n_steps): state -= (get_function_value(state) / get_function_derivative_value(state)) time_evolution = time() original_state = check_distance(state, roots) time_check = time() print_fractal(original_state) print("{0:<40}".format("Time to setup the initial configuration:"), "{:20.3f}".format(time_setup - time_start)) print("{0:<40}".format("Time to evolve the state:"), "{:20.3f}".format(time_evolution - time_setup)) print("{0:<40}".format("Time to check the closest roots:"), "{:20.3f}".format(time_check - time_evolution))  An average output looks like this: Time to setup the initial configuration: 0.004 Time to evolve the state: 0.796 Time to check the closest roots: 0.094 It's clear that it's the evolution part that bottlenecks the process. It's not "slow", but I think it's not enough to render something live like in the video. I already did what I could by using numpy vectors and avoiding loops but I guess it's not enough. What other tricks could be applied here? Note: I tried using numpy.polynomials.Polynomial class to evaluate the function, but it was slower than this version.

Answer:  I got an improvement (~40% faster) by using single complex (np.complex64) precision.  (...) state = np.transpose((np.linspace(c[0] - s/2, c[0] + s/2, n)[:, None] + 1j*np.linspace(c[1] - s/2, c[1] + s/2, n))) state = state.astype(np.complex64) (...)   3Blue1Brown added this link in the description: https://codepen.io/mherreshoff/pen/RwZPazd You can take a look how it was done there (sidenote: author of this pen used single precision as well)
Question: I want to create a 3D surface plot in Plotly by reading the data from an external file. Following is the code I am using:  import numpy as np import plotly.graph_objects as go import plotly.express as px data = np.genfromtxt('values.dat', dtype=float) # The shape of X, Y and Z is (10,1) X = data[:,0:1] Y = data[:,1:2] Z = data[:,2:3] fig = go.Surface(x=X, y=Y, z=Z, name='Surface plot', colorscale=px.colors.sequential.Plotly3) plot(fig)  The above code does not produce any surface plot. What changes has to be made to create a surface plot?

Answer: From plotly figure reference: The data the describes the coordinates of the surface is set in z. Data in z should be a 2D list. Coordinates in x and y can either be 1D lists or {2D arrays} I have an example data set. It contains three columns (x,y,z). import plotly.graph_objects as go import pandas as pd import numpy as np from scipy.interpolate import griddata df = pd.read_csv('./test_data.csv') x = np.array(df.lon) y = np.array(df.lat) z = np.array(df.value) xi = np.linspace(x.min(), x.max(), 100) yi = np.linspace(y.min(), y.max(), 100) X,Y = np.meshgrid(xi,yi) Z = griddata((x,y),z,(X,Y), method='cubic') fig = go.Figure(go.Surface(x=xi,y=yi,z=Z)) fig.show()  Reference Page: https://plotly.com/python/reference/surface/
Question: I have CSV file with data: Number 1.1 2.2 4.1 5.4 9.176 14.54345774 16.25664  If I print to display with pandas I get: df = pd.read_csv('data.csv') print(df) Number 0 1.100000 1 2.200000 2 4.100000 3 5.400000 4 9.176000 5 14.543458 6 16.256640  But if I cut 14.54345774 to 14.543 output is changed:  Number 0 1.10000 1 2.20000 2 4.10000 3 5.40000 4 9.17600 5 14.54300 6 16.25664  The first case number of digits after decimal point in pandas is 6, second case is 5. Why format is changed? What pandas parameters should I change so these cases are equal? I want the number of digits after the decimal point to be constant and digits after the decimal point is round to max digits after the decimal point if it possibly. UPDATE: IMO, This moment arises on data initialization, so round don't get to desirable result if I want use 6 digits. It only can be decreased (6->5 digits), but it can't be increased (5->6).

Answer: You can use pd.set_option to set the decimal number display precision to e.g. 5 in this case: pd.set_option("display.precision", 5)  or use: pd.options.display.float_format = '{:.5f}'.format  Result: print(df) # with original value of 14.54345774 Number 0 1.10000 1 2.20000 2 4.10000 3 5.40000 4 9.17600 5 14.54346 6 16.25664
Question: What should go in my Procfile for a Django application on Heroku? I tried: web: python appname.py  because I found an example like that for python apps. Further searching didn't make things any clearer except for that I might need to use gunicorn instead of python. I found various posts suggesting various formats such as: web gunicorn web:gunicorn web: gunicorn  I have no clue what should come after gunicorn, some posts have the programming language, some have an IP address, some have various other things. Some suggest running: heroku ps:scale web=1  but that results in an error: Scaling dynos... ! ! Couldn't find that process type (web).  I just haven't got a clue and don't know where to turn. Since posting I have watched some videos about this and tried: web: gunicorn appname.wsgi  in my Procfile but it still doesn't work, still resulting in: at=error code=H14 desc="No web processes running" 

Answer: Heroku's Procfile format is quite simple. As described in the documentation:  A Procfile declares its process types on individual lines, each with the following format: <process type>: <command>   You can see that there should be a colon after the process type, so the web gunicorn  example in your question is not going to work properly. You'll want to start the line with web:.  <command> indicates the command that every dyno of the process type should execute on startup, such as rake jobs:work  For Django, in development you'd typically use python manage.py runserver to run the application, so a reasonable attempt for Django would be web: python manage.py runserver  This should work, but it's not appropriate for production work:  DO NOT USE THIS SERVER IN A PRODUCTION SETTING. It has not gone through security audits or performance tests. (And that’s how it’s gonna stay. We’re in the business of making Web frameworks, not Web servers, so improving this server to be able to handle a production environment is outside the scope of Django.)  Instead, you should use a production-grade web server in production. Gunicorn is a common choice, and you can run your Django application with Gunicorn like so: gunicorn myproject.wsgi  Putting that all together, a Procfile for Django on Heroku might look like web: gunicorn myproject.wsgi  where myproject is the name of your Django project. This is exactly what Heroku's documentation suggests for Django applications. Note that you'll have to add Gunicorn to your project dependencies so Heroku will install it. I recommend also installing it locally so you can use heroku local to test your application on your dev machine in a way more similar to Heroku's production environment. heroku ps:scale is used to change the number and type of dynos for process types you have already defined. It has nothing to do with defining those process types. That's what your Procfile is for.
Question: I created a virtual environment in python, now while activating the same from my command line in vscode I am getting the error PS C:\Users\hpoddar\Desktop\WebDev\ReactComplete\DjangoReact\ArticlesApp\APIProject> ..\venv\scripts\activate ..\venv\scripts\activate : File C:\Users\hpoddar\Desktop\WebDev\ReactComplete\DjangoReact\ArticlesApp\venv\scripts\Activate.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170. At line:1 char:1 + ..\venv\scripts\activate + ~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : SecurityError: (:) [], PSSecurityException + FullyQualifiedErrorId : UnauthorizedAccess  This is my project structure  However if I activate the same from my command line, it works without any error. Python version : 3.9.2 

Answer: A way is changing the terminal in VSCode to Command Prompt instead of PowerShell.  Open the drop-down on the right of the terminal and choose Select Default Profile   Select Command Prompt from the options.    Or, you can also set the execution policy to RemoteSigned or Unrestricted in PowerShell Note: This only affects the current user  Open PowerShell  Run the following command: Set-ExecutionPolicy RemoteSigned -Scope CurrentUser OR Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope CurrentUser   (Remove -Scope CurrentUser to apply to all users)
Question: I was figuring out how to do floor/ceiling operations without the math module. I solved this by using floor division //, and found out that the negative "gives the ceiling". So this works: >>> 3//2 1 >>> -3//2 -2  I would like the answer to be positive, so first I tried --3//2, but this gives 1. I inferred this is because Python evaluates -- to +. So to solve this, I found out I could use -(-3//2)), problem solved. But I came over another solution to this, namely (I included the previous example for comparison): >>> --3//2 # Does not give ceiling 1 >>> 0--3//2 # Does give ceiling 2  I am unable to explain why including the 0 helps. I have read the documentation on division, but I did not find any help there. I thought it might be because of the evaluation order: If I use --3//2 as an example, from the documentation I have that Positive, negative, bitwise NOT is strictest in this example, and I guess this evaluates -- to +. Next comes Multiplication, division, remainder, so I guess this is +3//2 which evaluates to 1, and we are finished. I am unable to infer it from the documentation why including 0 should change the result. References:  6.7. Binary arithmetic operations 6.14. Evaluation order 

Answer: Python uses the symbol - as both a unary (-x) and a binary (x-y) operator. These have different operator precedence. In specific, the ordering wrt // is:  unary - binary // binary -  By introducing a 0 as 0--3//2, the first - is a binary - and is applied last. Without a leading 0 as --3//2, both - are unary and applied together. The corresponding evaluation/syntax tree is roughly like this, evaluating nodes at the bottom first to use them in the parent node:  ---------------- ---------------- | --3//2 | 0--3//2 | |================|================| | | ------- | | | | 0 - z | | | | -----+- | | | | | | -------- | ----+--- | | | x // y | | | x // y | | | -+----+- | -+----+- | | | | | | | | | ----+ +-- | ---+ +-- | | | --3 | | 2 | | | -3 | | 2 | | | ----- --- | ---- --- | ---------------- ----------------  Because the unary - are applied together, they cancel out. In contrast, the unary and binary - are applied before and after the division, respectively.
Question: When I use a match-case statement in Python in VS Code, it gives red squiggly lines and errors in the "problems" tab: 

Answer: I got a response from one of the vscode-python devs on GitHub:  Unfortunately Jedi (and it's underlying parser, parso) has not added support for the match statement yet. Please consider switching your language server to "Default"/"Pylance" as our Pylance language server already has support.   As soon as Jedi makes a new release with match statement support we will take the update, but otherwise this is out of our hands. Since we have a language server that has support I'm a closing this issue.
Question: Python version : 3.10 I was trying to install the freegames python package using the following pip command C:\Users\praty>pip install freegames Defaulting to user installation because normal site-packages is not writeable Collecting freegames Downloading freegames-2.3.2-py2.py3-none-any.whl (108 kB) |████████████████████████████████| 108 kB 504 kB/s Installing collected packages: freegames Successfully installed freegames-2.3.2  But while importing the same on my python environment I was getting this error C:\Users\praty>python Python 3.10.0 (tags/v3.10.0:b494f59, Oct 4 2021, 19:00:18) [MSC v.1929 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import freegames Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\praty\AppData\Roaming\Python\Python310\site-packages\freegames\_init_.py", line 61, in <module> from .utils import floor, line, path, square, vector File "C:\Users\praty\AppData\Roaming\Python\Python310\site-packages\freegames\utils.py", line 77, in <module> class vector(collections.Sequence): AttributeError: module 'collections' has no attribute 'Sequence'  How do I resolve the same?

Answer: For quite some time Sequence was importable from collections: $ python2.7 -c "from collections import Sequence" $ python3.4 -c "from collections import Sequence" $ python3.5 -c "from collections import Sequence" $ python3.6 -c "from collections import Sequence"  Starting from Python 3.7 there was a warning the class has been moved to collections.abc: $ python3.7 -c "from collections import Sequence" -c:1: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3,and in 3.9 it will stop working $ python3.8 -c "from collections import Sequence" <string>:1: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3, and in 3.10 it will stop working $ python3.9 -c "from collections import Sequence" <string>:1: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3, and in 3.10 it will stop working  In Python 3.10 this became an error: $ python3.10 -c "from collections import Sequence" Traceback (most recent call last): File "<string>", line 1, in <module> ImportError: cannot import name 'Sequence' from 'collections' (/home/phd/.local/lib/python3.10/collections/__init__.py) $ python3.10 -c "from collections.abc import Sequence"  Report the problem to the author of freegames. Downgrade to Python 3.9. Learn that you should never be so fast to upgrade to the latest and greatest versions.
Question: I would like to get proper linting and type hints by [PyFlakes, Pylint] and mypy. For example, in the following code, we cannot get type error for the last line. We cannot even know if float_input exists. import argparse parser = argparse.ArgumentParser() parser.add_argument('--float_input', type=float) args = parser.parse_args() def int_sum(a: int, b: int): return a + b c = int_sum(args.float_input, args.float_input)  Is there a good way to improve this?

Answer: You can use typed-argument-parser to provide type hints for your arguments. You can define your arguments in a typesafe manner. from typing import Optional from tap import Tap class FooArgumentParser(Tap): float_input: Optional[float] = None args = FooArgumentParser().parse_args() def int_sum(a: int, b: int): return a + b c = int_sum(args.float_input, args.float_input) c = int_sum(args.foo, args.bar)  which gives you: foo.py:13:13: error: Argument 1 to "int_sum" has incompatible type "Optional[float]"; expected "int" foo.py:13:31: error: Argument 2 to "int_sum" has incompatible type "Optional[float]"; expected "int" foo.py:14:13: error: "FooArgumentParser" has no attribute "foo" foo.py:14:23: error: "FooArgumentParser" has no attribute "bar"  For required arguments, note that:  Variables defined as name: type are required arguments while variables defined as name: type = value are not required and default to the provided value.  You have to give the argument a default value to make it optional.