eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: I have a facebook authentication in my project, and I've set up some pipelines. So It would be nice for non-social email registration to also utilize these pipelines. I tried adding EmailAuth to the authentication backends list, but I don't know what view to use now for registratioin. So, is it possible (or reasonable) to use EmailAuth with drf-social-oauth2 for non-social registration, and if so, how do I do it?

Answer: You can integrate EmailAuth with drf-social-oauth2 by adding it to AUTHENTICATION_BACKENDS and using the same authentication pipelines. Since drf-social-oauth2 lacks a native email registration view, create a custom API endpoint that registers users manually and authenticates them via the email backend. Then, expose this view in your urls settings.py AUTHENTICATION_BACKENDS = ( 'social_core.backends.email.EmailAuth', # The email-based autentication 'social_core.backends.facebook.FacebookOAuth2', # Facebook login 'django.contrib.auth.backends.ModelBackend', # Default auth backend )  custom registration view # Other imports .. from rest_framework.status import HTTP_400_BAD_REQUEST, HTTP_201_CREATED from rest_framework.permissions import AllowAny from social_django.utils import load_backend, load_strategy from rest_framework.serializers import CharField, EmailField, Serializer class EmailRegistrationSerializer(Serializer): email = EmailField() password = CharField(max_length=100) member_type = CharField(max_length=20) class EmailRegisterView(APIView): permission_classes = [AllowAny] def post(self, request): serializer = EmailRegistrationSerializer(data=request.data) serializer.is_valid(raise_exception=True) strategy = load_strategy(request) backend = load_backend(strategy, "email", redirect_uri=None) user = backend.authenticate( response=serializer.data, backend=backend, strategy=strategy, request=request, ) return Response({"detail": "User registered successfully"}, HTTP_201_CREATED)  urls.py urlpatterns = [ # ... path("auth/register/email/", EmailRegisterView.as_view(), name="email_register"), ]
Question: I am trying to graph this function in manim x^(2/3) + 0.9sqrt(3.5-x^2) * sin(πx*a) I wrote some simple code to graph it in an animation like style: from manim import * import numpy as np class HeartAnimation(Scene): def construct(self): axes = Axes( x_range=[-10, 10, 1], y_range=[-7, 7, 1], axis_config={"color": BLUE}, ) def heart_curve(x): value = 3.5-x**2 return np.cbrt(x**2) + 0.9*value*np.sin(np.pi * x * 15) graph = axes.plot( heart_curve, color=RED, x_range=[-np.sqrt(3.5), np.sqrt(3.5)], use_smoothing=False ) self.play(Create(axes)) self.play(Create(graph)) self.wait(8)  the result from this code is this:  and what I was looking for is something like this in desmos  is there someway I can mess with the scaling or zooming to achieve something similar to what is produced in desmos? It doesn't have to be a one to one replicate, but it would be good if more of the heart show and the y axis to be scaled properly as it seems to be stretched in the y axis in manim when compared to desmos.

Answer: for the sampling rate, you have to add a third element (which will be the step of your sampling). However it seems like you can't make it too low, so to work aroud this problem, you can just scale the whole thing to be bigger (on both x and y so that shape doesn't change (in the formulas: x->x/scale and y->y*scale) for that I added a stretch_factor to the code. (as the sampling rate is higher, the density of curve increase, don't forget to lower the stroke_width in the plot method) stroke_width=1  and for the shape, I have reworked your formula by using a heart shaped double parabola instead of cuberoot function. here is the code : from manim import * import numpy as np class HeartAnimation(Scene): def construct(self): axes = Axes( x_range=[-100, 100, 10], y_range=[-70, 70, 10], axis_config={"color": BLUE}, ) def heart_curve(x): stretch_factor = 2 sinus_amp = 10 x = x/stretch_factor heart_shaped_parabola = max(-((x-8)/2)**2+25,-((x+8)/2)**2+25) sinus = sinus_amp*(3.5-(abs(x)/10)**3)*np.sin(np.pi * (x/10) * 15)-sinus_amp*(3.5-(x/10)**2) y = heart_shaped_parabola+sinus return y graph = axes.plot( heart_curve, color=RED, x_range=[-np.sqrt(3.5)*16.6, np.sqrt(3.5)*16.6,0.1], use_smoothing=False, stroke_width=1 ) self.play(Create(axes)) self.play(Create(graph)) self.wait(8)  hope this helps you
Question: I am trying to calculate a moving median for around 10.000 signals that each are a list of length around 750. An example dataframe looks like this: num_indices = 2000 # Set number of indices # Generate lists of values (each a list of numbers from 0 to 1) column_data = [np.random.random(750).tolist() for _ in range(num_indices)] # Create DataFrame df = pd.DataFrame({'values': column_data}, index=range(num_indices))  I have found this implementation that uses np.lib.stride_tricks, but it is a bit slow for my purpose. Does anyone have an idea for a faster method? def moving_median(signal,n=150): # Compute rolling median for valid windows swindow = np.lib.stride_tricks.sliding_window_view(signal, (n,)) b = np.nanmedian(swindow, axis=1) b_full = np.concatenate([[np.nanmedian(signal)]*(n-1), b]) # Prepend first `n-1` values unchanged return signal - b_full  And finally: df.iloc[:,0].apply(lambda x: moving_median(x)) 

Answer: You don't mention having NaNs in your data, so I will assume you do not. In that case, I think this is the best SciPy has to offer: import numpy as np from scipy.ndimage import median_filter rng = np.random.default_rng(49825498549428354) data = rng.random(size=(2000, 750)) # 2000 signals, each of length 750 res = median_filter(data, size=(150,), axes=(-1,)) # moving window of size 150  I believe there was some recent work done to make this faster in the development version of SciPy (nightly wheels here) than before. I'm guessing that rather than re-sorting each window from scratch, it updates a sorted or partitioned data structure based on the incoming and outgoing values, but I haven't really looked into it. Note the various mode options in the documentation that control what happens at the boundary. If you are happy to get back an array that is smaller than the original rather the default "reflect" boundary condition, you may just want to use the default mode and trim the edges afterwards. If you do have NaNs, SciPy has a new vectorized_filter that will work with np.nanmedian, but it just uses stride_tricks.sliding_window_view under the hood, so unlikely to be faster than what you have. If CuPy is an option, let me know, and I might be able to suggest something much faster. SciPy's median_filter still isn't as fast as it should be.
Question: I have a dataframe with below data.    DateTime Tag Qty     2025-01-01 13:00 1 270   2025-01-03 13:22 1 32   2025-01-10 12:33 2 44   2025-01-22 10:04 2 120   2025-01-29 09:30 3 182   2025-02-02 15:05 1 216    To be achieved: 2 new columns, first with cumulative sum of Qty until the DateTime on each row when Tag is not equal to 2, second with cumulative sum of Qty until the DateTime on each row when Tag is equal to 2. Below is the result I am looking for.    DateTime Tag Qty RBQ RSQ     2025-01-01 13:00 1 270 270 0   2025-01-03 13:22 1 32 302 0   2025-01-10 12:33 2 44 302 44   2025-01-22 10:04 2 120 302 164   2025-01-29 09:30 3 182 484 164   2025-02-02 15:05 1 216 600 164    I've been searching for a method, but doesn't seem to be getting it right. May I please get help on getting it right? Thanks,

Answer: You can use a condition and the methods mask and where to create both columns cond = df['Tag'].eq(2) df['RBQ'] = df['Qty'].mask(cond, 0).cumsum() df['RSQ'] = df['Qty'].where(cond, 0).cumsum()  Another solution is to use the same condition and pivot the dataframe based on that. df2 = (df.join(df.assign(cols=df['Tag'].eq(2).map({True: 'RSQ', False: 'RBQ'})) .pivot(columns='cols', values='Qty') .fillna(0).cumsum()) )  End result:  DateTime Tag Qty RBQ RSQ 2025-01-01 13:00 1 270 270.0 0.0 2025-01-03 13:22 1 32 302.0 0.0 2025-01-10 12:33 2 44 302.0 44.0 2025-01-22 10:04 2 120 302.0 164.0 2025-01-29 09:30 3 182 484.0 164.0 2025-02-02 15:05 1 216 700.0 164.0  Edit: Here is a slightly modified version that takes in consideration the DateTime column. I modified the first value in the datetime column as an example. cond = df['Tag'].eq(2) tmp = df.sort_values(by='DateTime') df['RBQ'] = tmp['Qty'].mask(cond, 0).cumsum() df['RSQ'] = tmp['Qty'].where(cond, 0).cumsum()  For the second solution, you will have to use merge instead of join. df2 = pd.merge(df, (df.assign(cols=df['Tag'].eq(2).map({True: 'RSQ', False: 'RBQ'})) .pivot(index='DateTime', columns='cols', values='Qty') .fillna(0).cumsum()), on='DateTime')  End result:  DateTime Tag Qty RBQ RSQ 2025-02-04 13:00:00 1 270 700.0 164.0 2025-01-03 13:22:00 1 32 32.0 0.0 2025-01-10 12:33:00 2 44 32.0 44.0 2025-01-22 10:04:00 2 120 32.0 164.0 2025-01-29 09:30:00 3 182 214.0 164.0 2025-02-02 15:05:00 1 216 430.0 164.0
Question: I have a nested json, but I can't understand how to work with them. { "return": { "status_processing": "3", "status": "OK", "order": { "id": "872102042", "number": "123831", "date_order": "dd/mm/yyyy", "items": [ { "item": { "id_product": "684451795", "code": "VPOR", "description": "Product 1", "unit": "Un", "quantity": "1.00", "value": "31.76" } }, { "item": { "id_product": "684451091", "code": "VSAP", "description": "Product 2", "unit": "Un", "quantity": "1.00", "value": "31.76" } } ] } } }  I searched on stackoverflow questions, and try some resolutions that people passed, but don't work for me. Here an sample that I used to accessing the data from json: df = pd.json_normalize( order_list, record_path=["return", "order", "itens"], meta=[ ["return", "order", "id"], ["return", "order", "date_order"], ["return", "order", "number"], ], )  But don't work, they duplicating the data when I send to dataframe. Anyone can help me? EDIT Here an example that I used: Convert nested JSON to pandas DataFrame And what I expected: 

Answer: I don't know what exactly you expect in output but if you want every item in new row then you could use normal code with for-loop for this. order_list = { "return": { "status_processing": "3", "status": "OK", "order": { "id": "872102042", "number": "123831", "date_order": "dd/mm/yyyy", "itens": [ { "item": { "id_product": "684451795", "code": "VPOR", "description": "Product 1", "unit": "Un", "quantity": "1.00", "value": "31.76" } }, { "item": { "id_product": "684451091", "code": "VSAP", "description": "Product 2", "unit": "Un", "quantity": "1.00", "value": "31.76" } } ] } } } import pandas as pd data = [] order = order_list['return']['order'] for iten in order['itens']: for key, val in iten.items(): row = { #'key': key, 'id': order['id'], 'date_order': order['date_order'], 'number': order['number'], 'id_product': val['id_product'], #'code': val['code'], #'description': val['description'], #'quantity': val['quantity'], #'value': val['value'], } data.append(row) df = pd.DataFrame(data) print(df)  Result:  id date_order number id_product 0 872102042 dd/mm/yyyy 123831 684451795 1 872102042 dd/mm/yyyy 123831 684451091  If you need other information in rows then you should show it in question.
Question: I'm using the pandas library to convert CSVs to other data types. My CSV has the fields quoted, like this: "Version", "Date", "Code", "Description", "Tracking Number", "Author" "0.1", "22AUG2022", , "Initial Draft", "NR", "Sarah Marshall" "0.2", "23SEP2022", "D", "Update 1", "N-1234", "Bill Walter" "0.3", "09MAY2023", "A\, C", "New update.", "N-1235", "George Orwell"  The problem is that when I read the CSV with pandas.read_csv('myfile.csv'), the quotes are included in the values:  Version "Date" "Code" "Description" "Tracking Number" "Author" 0 0.1 "22AUG2022" "Initial Draft" "NR" "Sarah Marshall" 1 0.2 "23SEP2022" "D" "Update 1" "N-1234" "Bill Walter" 2 0.3 "09MAY2023" "A, C" "New update." "N-1235" "George Orwell"  So these quotes are included when converting to HTML: <table> <thead> <tr style="text-align: right"> <th></th> <th>Version</th> <th>"Date"</th> <th>"Code"</th> <th>"Description"</th> <th>"Tracking Number"</th> <th>"Author"</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>0.1</td> <td>"22AUG2022"</td> <td></td> <td>"Initial Draft"</td> <td>"NR"</td> <td>"Sarah Marshall"</td> </tr> ...  I've tried quoting=csv.QUOTE_NONE, but it didn't fix it--in fact, it actually added quotes to the Version column. I found this question--the answers essentially says to strip out any quotes in post processing. I can of course loop through the CSV rows and strip out the leading/trailing quotes for each of the values, but since quoted values are common with CSV I'd expect that there would be a parameter or easy way to enable/disable the quotes in the rendered output but I can't find something like that. Is there a way to accomplish this?

Answer: The leading spaces in your input seem to be throwing Pandas off (and some other CSV processors I can think of). Try the skipinitialspace=True option to make Pandas ignore every space between a comma and a quote char: import pandas as pd df = pd.read_csv("input.csv", skipinitialspace=True) print(df)   Version Date ... Tracking Number Author 0 0.1 22AUG2022 ... NR Sarah Marshall 1 0.2 23SEP2022 ... N-1234 Bill Walter 2 0.3 09MAY2023 ... N-1235 George Orwell [3 rows x 6 columns]  Expounding a bit, you can see the difference, where quotes are present, between the default of not skipping the initial space and skipping: from io import StringIO data = """ Col1 "foo" "foo" " foo" """.strip() print("no skip") df = pd.read_csv(StringIO(data)) for _, x in df.iterrows(): print(repr(x["Col1"])) print() print("skip initial") df = pd.read_csv(StringIO(data), skipinitialspace=True) for _, x in df.iterrows(): print(repr(x["Col1"]))  no skip 'foo' ' "foo"' ' foo' skip initial 'foo' 'foo' ' foo'   "foo" doesn't matter as it doesn't have any space  "foo" is up for interpretation as the space precedes the (default) quote char " foo" also doesn't matter as the space is encoded inside the (default) quote char
Question: In my django web app i am trying to build a Newspaper app, in my homepage when i click on SIGN UP Button i get an error "ImproperlyConfigured at /accounts/signup/", I didnt figure out where is the problem. forms.py: from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): #Creation of CustomUser class Meta: model = CustomUser fields = UserCreationForm.Meta.fields + ("age",) class CustomUserChangeForm(UserChangeForm): #Modifying existing users class Meta: model = CustomUser fields = UserChangeForm.Meta.fields  and models.py: from django.contrib.auth.models import AbstractUser #username, pw1, pw2 from django.db import models class CustomUser(AbstractUser): age = models.PositiveIntegerField(null=True, blank=True)  urls.py: from django.urls import path from .views import SignUpView #Accounts/urls.py : Handles only registrations URLs!! urlpatterns = [ path('signup/', SignUpView.as_view(), name='signup'), ]  and views.py: from django.urls import reverse_lazy from django.views.generic import CreateView from .forms import CustomUserCreationForm class SignUpView(CreateView): from_class = CustomUserCreationForm success_url = reverse_lazy('login') template_name = 'registration/signup.html'  signup.html:  {% extends 'base.html' %} {% block title %}Sign Up{% endblock title %} {% block content %} <h2>Sign Up</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Sign Up</button> </form> {% endblock content %}  I tried to change fields in forms.py with: fields = ( "username", "email", "age",)  but nothing to be mention

Answer: The culprit is a typo: from_class to form_class: from django.urls import reverse_lazy from django.views.generic import CreateView from .forms import CustomUserCreationForm class SignUpView(CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('login') template_name = 'registration/signup.html' But I think it is interesting to know why this then raises this error: if you don't provide a .form_class [Django-doc] to a CreateView, a CreateView will try to make its own form, for that it can work with the modelform_factory(…) [Django-doc], but for that it needs to know the model. It tries to determine the model in three possible ways: first by looking if the view has a .model attribute, if not if it has an .object attribute (for an UpdateView the form can be implied by the object to update), and finally it runs the .get_queryset() method [Django-doc] to obtain the model of the QuerySet, and since none of these work with this SignUpView, we thus get that error.
Question: Numpy has many nice features for formatted output, but something I miss is the ability to print more than one array/matrix on the same line. What I mean is easiest to explain with an example. Given the following code: A = np.random.randint(10, size = (4, 4)) B = np.random.randint(10, size = (4, 4)) niceprint(A, "*", B, "=", A @ B)  How can you implement niceprint so that it prints the following on the console? [[7 1 0 4] [[8 6 2 6] [[ 80 45 54 83] [8 1 5 8] * [0 3 8 5] = [147 91 123 140] [3 7 2 4] [7 8 7 3] [ 62 55 108 95] [8 8 2 8]] [6 0 8 9]] [126 88 158 166]] 

Answer: Don't write it yourself; use something common and off-the-shelf like Sympy. import numpy as np import sympy A = sympy.Matrix(np.random.randint(10, size=(4, 4))) B = sympy.Matrix(np.random.randint(10, size=(4, 4))) sympy.pretty_print( sympy.Eq( sympy.MatMul(A, B), A @ B, ) )  ⎡4 2 1 5⎤ ⎡3 0 7 7⎤ ⎡77 54 42 58 ⎤ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥ ⎢1 6 5 1⎥ ⎢9 5 0 1⎥ ⎢76 82 29 57 ⎥ ⎢ ⎥⋅⎢ ⎥ = ⎢ ⎥ ⎢3 3 7 0⎥ ⎢2 9 4 8⎥ ⎢50 78 49 80 ⎥ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥ ⎣7 6 2 8⎦ ⎣9 7 2 4⎦ ⎣151 104 73 103⎦
Question: I created some simple console games in Python(Oyna Project) and took screenshots of each game to showcase them in the README.md file. I wanted to display these images in a table format both on GitHub and on PyPI. On GitHub, everything looks fine — the images are well-aligned, and their sizes are consistent. But when I push this library(Oyna) to PyPI, the image sizes look uneven and unbalanced. The problem is that the images themselves are not the same size, and on PyPI, some images appear much smaller or larger than others, making the table look messy. I've tried adjusting the image sizes using HTML tags and Markdown syntax, but nothing seems to work correctly on PyPI. How can I make the images show up consistently and evenly on PyPI just like they do on GitHub, even if their original sizes are different? My code to display the table: <table> <tr> <td><a href="https://github.com/kamyarmg/oyna/tree/main/src/oyna/sudoku/"> Sudoku </a> </br><img src="https://raw.githubusercontent.com/kamyarmg/oyna/refs/heads/main/docs/images/sudoku.png" alt="Sudoku" style="width:250px;"/> </td> <td><a href="https://github.com/kamyarmg/oyna/tree/main/src/oyna/twenty_forty_eight_2048/">2048</a> </br><img src="https://raw.githubusercontent.com/kamyarmg/oyna/refs/heads/main/docs/images/2048.png" alt="2048" style="width:250px;"/> </td> <td><a href="https://github.com/kamyarmg/oyna/tree/main/src/oyna/matching/">Matching</a> </br><img src="https://raw.githubusercontent.com/kamyarmg/oyna/refs/heads/main/docs/images/matching.png" alt="Matching" style="width:250px;"/> </td> </tr> </table>  Github README.md Image Table:  Pypi Image Table: 

Answer: You can solve this issue by resizing the images via usage of html table format since PyPi supports HTML in its Readme files, find a way to tweak the width and or the height, however monitor the aspect ratio of the image and perhaps focus only on the width of the image since most browser calculate other dimension for you to avoid distortion of your image. For example, here is a way you can go with it on your Readme file: <table> <tr> <td> <img src="my imageA.png" width="180"> </td> </tr> </table>
Question: ref: ISystemMediaTransportControlsInterop I compiled a dll about ISystemMediaTransportControlsInterop::GetForWindow. I use IDA to decompile it. Then I wrote the C-like code as Python. I believe that I was wrote them in a right way. But sadly, I met a pointer error. I know it's because SMTC_Interop_GetForWindow function address is incorrect, but I don't know why. Python log: RoInit: 0 String Create: 0, SMTCInterop: c_void_p(None) RoGetActivationFactory: 0, SMTCInterop: c_void_p(7948368) Traceback (most recent call last): File "D:\儿子文件\编程\python\PyCharm项目\WinSMTC\test.py", line 56, in <module> TestFunc() File "D:\儿子文件\编程\python\PyCharm项目\WinSMTC\test.py", line 45, in TestFunc GetForWindow(Create_SMTC_Window(), smtc_obj) File "D:\儿子文件\编程\python\PyCharm项目\WinSMTC\test.py", line 26, in GetForWindow result = SMTC_Interop_GetForWindow(smtc_interop.value, hwnd, ctypes.byref(REF_IID), ctypes.byref(smtc_obj)) OSError: exception: access violation writing 0x00007FFBED118788  Python Code(key func): def GetForWindow(hwnd: int, smtc_obj: ctypes.c_void_p): result = RoInitialize(RO_INIT_MULTITHREADED) print("RoInit:", result) smtc_interop = VoidPtr() h_string = HSTRING() result = WindowsCreateString(String("Windows.Media.SystemMediaTransportControls"), ctypes.c_uint32(42), ctypes.byref(h_string)) print(f"String Create: {result}, SMTCInterop: {smtc_interop}") result = RoGetActivationFactory(h_string, ctypes.byref(IID_SystemMediaTransportControls), ctypes.byref(smtc_interop)) print(f"RoGetActivationFactory: {result}, SMTCInterop: {smtc_interop}") SMTC_Interop_GetForWindow = ctypes.CFUNCTYPE(ctypes.c_int64, ctypes.c_int64, ctypes.c_int32, ctypes.POINTER(ctypes.c_int64), ctypes.POINTER(ctypes.c_void_p))(ctypes.cast(smtc_interop.value, ctypes.POINTER(ctypes.c_int64)).contents.value + 48) result = SMTC_Interop_GetForWindow(smtc_interop.value, hwnd, ctypes.byref(REF_IID), ctypes.byref(smtc_obj))  IDA Func Code(to the key func):  You can download Dll Source Code & Dll File & IDA Debug File & Test Python Code in here

Answer: The error suggests you're trying to write to memory that's not accessible. The main problem is in this line: SMTC_Interop_GetForWindow = ctypes.CFUNCTYPE(...)(ctypes.cast(smtc_interop.value, ctypes.POINTER(ctypes.c_int64)).contents.value + 48)  Change it with vtable_ptr = ctypes.cast(smtc_interop.value, ctypes.POINTER(ctypes.c_void_p)).contents.value method_ptr = ctypes.cast(vtable_ptr + 3 * 8, ctypes.POINTER(ctypes.c_void_p)).contents.value SMTC_Interop_GetForWindow = ctypes.CFUNCTYPE(ctypes.c_int64, ctypes.c_void_p, ctypes.c_int32, ctypes.POINTER(ctypes.c_int64), ctypes.POINTER(ctypes.c_void_p))(method_ptr)  This approach should resolve the error as it accesses the function pointer through the vtable structure rather than using a direct offset from the interface pointer.