question_id int64 59.5M 79.7M | creation_date stringdate 2020-01-01 00:00:00 2025-07-15 00:00:00 | link stringlengths 60 163 | question stringlengths 53 28.9k | accepted_answer stringlengths 26 29.3k | question_vote int64 1 410 | answer_vote int64 -9 482 |
|---|---|---|---|---|---|---|
74,051,135 | 2022-10-13 | https://stackoverflow.com/questions/74051135/split-a-text-by-specific-word-or-phrase-and-keep-the-word-in-python | Is there any elegant way of splitting a text by a word and keep the word as well. Although there are some works around split with re package and pattern like (Python RE library String Split but keep the delimiters/separators as part of the next string), but none of them works for this scenario when the delimiter is rep... | Yes. What you're looking for is a feature of the re.split() method. If you use a capture group in the expression, it will return the matched terms as well: import re s = "I want to split text here, and also keep here, and return all as list items" r = re.split('(here)', s) print(r) Result: ['I want to split text ', 'h... | 4 | 4 |
74,047,903 | 2022-10-12 | https://stackoverflow.com/questions/74047903/django-channels-and-react-error-websocket-connection-to-ws-localhost8000-my | First-of-all, I still don't know whether the issue is on front-end or back-end side, but it seems like back-end is more likely. I have built a Django application using django-channels to send packets of data to a front-end react.js SPA via websocket connection; I've also built a simple vanilla-javascript client previou... | it happens when you attempts to close the WebSocket connection ws.close() before it's had a chance to actually connect. Try changing useEffect cleanup function : return () => ws.close(); to : return () => { if (socket.readyState === 1) { socket.close(); } | 3 | 5 |
74,047,721 | 2022-10-12 | https://stackoverflow.com/questions/74047721/prevent-selenium-from-taking-the-focus-to-the-opened-window | I have 40 Python unit tests and each of them open a Selenium driver as they are separate files and cannot share the same driver. from selenium import webdriver webdriver.Firefox() The above commands will take the focus to the new opened window. For example, if I am on my editor and typing something, in the middle of m... | Here is an example of running Selenium/Firefox on linux, in headless mode. You can see various imports as well - gonna leave them there. Browser will start in headless mode, will go to ddg page and print out the page source, then quit. from selenium.common.exceptions import NoSuchElementException, TimeoutException from... | 4 | 4 |
74,047,268 | 2022-10-12 | https://stackoverflow.com/questions/74047268/is-there-a-way-to-split-a-string-on-delimiters-including-colon-except-when-it | I am trying to split the string below on a number of delimiters including \n, comma(,), and colon(:) except when the colon is part of a time value. Below is my string: values = 'City:hell\nCountry:rome\nUpdate date: 2022-09-26 00:00:00' I have tried: result = re.split(':|,|\n', values) However, this ends up splitting... | You could use look-behind to ensure that what is before : is not a pair of digits re.split('(?<![0-9]{2}):\s*|,|\n', values) It separates by colons with optional spaces when they are not preceded by digits , \n So : is a separator (when not preceded by a pair of digits). But so is : or : (still, when they are not ... | 4 | 4 |
74,043,416 | 2022-10-12 | https://stackoverflow.com/questions/74043416/does-the-in-operator-have-side-effects | I have code which writes bytes to a serial port (pySerial 3.5) and then receives bytes. The code should work for micropython too, which uses UART instead of pySerial. With UART, I have to add a small delay before reading. The user should not have to pass an additional flag whether to add that delay, because the serial_... | As mentioned in a comment by deceze, in just calls the __contains__() method. Depending on how this is implemented, it can have side effects. A simple example to demonstrate this: class Example: def __contains__(self, x): print('Side effect!') x = Example() if 'something' in x: print('Found') else: print('Not found') ... | 3 | 3 |
74,042,960 | 2022-10-12 | https://stackoverflow.com/questions/74042960/find-the-index-value-when-the-value-changes-in-a-column-in-dataframe-pandas | I have a dataframes as follows: df1 = col_1 val_1 0 4.0 0.89 1 4.0 0.56 2 49.0 0.7 3 49.0 1.23 4 52.0 0.8 5 52.0 0.12 6 32.0 0.5 I want to find the index value when the value in col_1 changes and put in a list I tried the following: n_change = (np.where(~df1.col_1.diff(+1).isin([0, np.nan]))) But it returns a tuple o... | You can use: df.index[df['col_1'].ne(df['col_1'].shift().bfill())] # or with diff # df.index[df['col_1'].diff().fillna(0).ne(0)] output: Int64Index([2, 4, 6], dtype='int64') As list: df.index[df['col_1'].ne(df['col_1'].shift().bfill())].tolist() output: [2, 4, 6] With your solution: np.where(~df.col_1.diff().isin([0,... | 3 | 3 |
74,042,649 | 2022-10-12 | https://stackoverflow.com/questions/74042649/pandas-how-to-duplicate-a-value-for-every-substring-in-a-column | I have a pandas dataframe as folllows, import pandas as pd df = pd.DataFrame({'text': ['set an alarm for [time : two hours from now]','wake me up at [time : nine am] on [date : friday]','check email from [person : john]']}) print(df) original dataframe text 0 set an alarm for [time : two hours from now] 1 wake me up ... | You can use a regex with a custom function as replacement: df['new_text'] = df.text.str.replace( r"\[([^\[\]]*?)\s*:\s*([^\[\]]*)\]", lambda m: ' '.join([f'[{m.group(1)} : {x}]' for x in m.group(2).split()]), # new chunk for each word regex=True) output: text new_text 0 set an alarm for [time : two hours from now] se... | 3 | 2 |
74,037,740 | 2022-10-12 | https://stackoverflow.com/questions/74037740/can-i-use-a-context-manager-for-a-whole-module | I'd like to have a context manager that is opened (entered?) for the lifetime of the application. It should be opened when a module loads and be closed when the module is destroyed. Wrapping the whole module code won't work, since then the conetext manager is closed when the module is finished loading and is no longer ... | A context manager is not suitable for managing the lifecycle of an object across modules. Instead, you can register the close method of your aiohttp.ClientSession instance with the atexit module so that it would be called when the app stops for any reason. Since in this case the close method is a coroutine, register th... | 4 | 7 |
74,037,299 | 2022-10-12 | https://stackoverflow.com/questions/74037299/match-phone-number-using-regex-5x000y000 | I am trying to match the pattern 5X000Y000 of 9 digit number. What I have tried I have written the below regex B_5 = 530004000 B_5_pattern = re.sub(r'^5(\d(000))(\d(000))', "Bronze", str(B_5)) print(B_5_pattern) What I want to achieve I want to update my regex to add a condition that X000 can not be the same as Y000. ... | You could use: B_5 = "530004000" if re.search(r'^5(\d)0{3}(?!\1)\d0{3}$', B_5): print("MATCH") | 3 | 5 |
73,972,660 | 2022-10-6 | https://stackoverflow.com/questions/73972660/how-to-return-data-in-json-format-using-fastapi | I have written the same API application with the same function in both FastAPI and Flask. However, when returning the JSON, the format of data differs between the two frameworks. Both use the same json library and even the same exact code: import json from google.cloud import bigquery bigquery_client = bigquery.Client(... | The wrong approach If you serialize the object before returning it, using json.dumps() (as shown in your example), for instance: import json @app.get('/user') async def get_user(): return json.dumps(some_dict, indent=4, default=str) the JSON object that is returned will end up being serialized twice, as, in this case,... | 24 | 30 |
74,009,210 | 2022-10-10 | https://stackoverflow.com/questions/74009210/how-to-create-a-fastapi-endpoint-that-can-accept-either-file-form-or-json-body | I would like to create an endpoint in FastAPI that might receive either multipart/form-data or JSON body. Is there a way I can make such an endpoint accept either, or detect which type of data is receiving? | Option 1 You could have a dependency function, where you would check the value of the Content-Type request header and parse the body using Starlette's methods, accordingly. Note that just because a request's Content-Type header says, for instance, application/json, application/x-www-form-urlencoded or multipart/form-da... | 8 | 13 |
73,991,575 | 2022-10-7 | https://stackoverflow.com/questions/73991575/how-to-transform-polars-datetime-column-into-a-string-column | I'm trying to change a datetime column to a string column using polars library. I only want the dates on the new column: import polars as pl df = pl.from_repr(""" ┌─────────────────────┐ │ date_time │ │ --- │ │ datetime[ns] │ ╞═════════════════════╡ │ 2007-04-19 00:00:00 │ │ 2007-05-02 00:00:00 │ │ 2007-05-03 00:00:00 ... | You should try this: # Polars df = df.with_columns(pl.col('date_time').dt.strftime('%Y-%m-%d')) # Pandas df['date_time'] = df['date_time'].dt.strftime('%Y-%m-%d') Edit: added Polars | 4 | 5 |
73,991,045 | 2022-10-7 | https://stackoverflow.com/questions/73991045/how-to-specify-type-for-function-parameter-python | I want to restrict scope of functions that can be passed as parameter to another function. For example, to restrict functions to be only one from two specified, or from particular module, or by signature. I tried the code below but in it there is now restrictions: as parameter can be passed any function. Is this possib... | Frameworks expecting callback functions of specific signatures might be type hinted using Callable[[Arg1Type, Arg2Type], ReturnType] You might want to use the Callable type. This might help https://docs.python.org/3/library/typing.html#annotating-callable-objects NOTE Type annotations in Python are not make-or-break ... | 5 | 6 |
73,989,150 | 2022-10-7 | https://stackoverflow.com/questions/73989150/how-to-make-a-python-magicmock-object-json-serializable | I am using a Python Mock object for a third-party package that needs to JSON serialize my mock. This means that I cannot change the invocation of json.dumps, so must use the solution here: https://stackoverflow.com/a/31207881/19643198 class FileItem(dict): def __init__(self, fname): dict.__init__(self, fname=fname) f =... | There is no need to consider multiple inheritance. The problem is that Python's JSON module doesn't know how to serialize certain types, like MagicMock (or other common types like datetime, for that matter). You can tell json how to deal with unknown types by either using the cls= or default= parameters, but since you ... | 5 | 2 |
73,962,743 | 2022-10-5 | https://stackoverflow.com/questions/73962743/fastapi-is-not-returning-cookies-to-react-frontend | Why doesn't FastAPI return the cookie to my frontend, which is a React app? Here is my code: @router.post("/login") def user_login(response: Response,username :str = Form(),password :str = Form(),db: Session = Depends(get_db)): user = db.query(models.User).filter(models.User.mobile_number==username).first() if not user... | First, create the cookie, as shown in the example below, and make sure there is no error returned when performing the Axios POST request, and that you get a 'status': 'success' response with 200 status code. You may want to have a look at this answer as well, which provides explains how to use the max_age and expires f... | 6 | 14 |
73,989,179 | 2022-10-7 | https://stackoverflow.com/questions/73989179/install-usd-pixar-library | I have some trouble for installing USD library on Ubuntu. Here is the tuto I want to follow. On github, I cloned the git, run the script build_usd.py and change the env var. But when I want to run this simple code from pxr import Usd, UsdGeom stage = Usd.Stage.CreateNew('HelloWorld.usda') xformPrim = UsdGeom.Xform.Defi... | You should install usd-core library, which has the pxr module pip install usd-core | 3 | 5 |
74,027,680 | 2022-10-11 | https://stackoverflow.com/questions/74027680/pytorch-profiler-with-scheduler-prints-unwanted-message-at-step | I am trying to learn how to use the Pytorch profiler API to measure the difference in performance when training a model using different methods. In the dedicated tutorial, there is one part where they show how to do just that using the "schedule" parameter of the profiler. My problem is that when I want to use it in my... | This was just recently fixed/added in a pull request now you can set the env variable KINETO_LOG_LEVEL. For example in a bash script: export KINETO_LOG_LEVEL=3 The levels according to the source code are: enum LoggerOutputType { VERBOSE = 0, INFO = 1, WARNING = 2, ERROR = 3, STAGE = 4, ENUM_COUNT = 5 }; Thats atleast ... | 6 | 1 |
74,010,813 | 2022-10-10 | https://stackoverflow.com/questions/74010813/fastapi-how-can-i-modify-request-from-inside-dependency | How can I modify request from inside a dependency? Basically I would like to add some information (test_value) to the request and later be able to get it from the view function (in my case root() function). Below is a simple example: from fastapi import FastAPI, Depends, Request app = FastAPI() def test(request: Reques... | Option 1 You could store arbitrary extra state to request.state, and use the Request object inside the endpoint to retrieve the state (the relevant implementation of Starlette's State method and class can be found here and here, respectively): from fastapi import FastAPI, Depends, Request app = FastAPI() def func(reque... | 6 | 11 |
73,997,704 | 2022-10-8 | https://stackoverflow.com/questions/73997704/how-can-i-use-celery-in-django-with-just-the-db | Looking at https://docs.celeryq.dev/en/v5.2.7/getting-started/backends-and-brokers/index.html it sounds pretty much as if it's not possible / desirable. There is a section about SQLAlchemy, but Django does not use SQLAlchemy. In way older docs, there is https://docs.celeryq.dev/en/3.1/getting-started/brokers/django.htm... | Yes you can totally do this, even if it's not the most performant/recommended way to do. I use it for simple projects in which I don't want to add Redis. To do so, first, add SQLAlchemy v1 as a dependency in your project: SQLAlchemy = "1.*" Then in your settings.py: if you use PostgreSQL: CELERY_BROKER_URL = sqla+pos... | 3 | 5 |
74,001,347 | 2022-10-9 | https://stackoverflow.com/questions/74001347/django-autocomplete-light-not-working-with-bootstrap-5-modal | I am newbie to Python and Django. I'm using DAL on a form inside a Bootstrap modal. Clicking the dropdown list appears behind the modal. The autocomplete function works correctly if I do it outside of the modal. I'm using: Django: 4.0.5 django-autocomplete-light: 3.9.4 Bootstrap 5.2.2 Python 3.10.4 To try to fix it, I ... | The problem is modal focus, so if you review the documentation https://getbootstrap.com/docs/5.3/components/modal/#options in options there's a definition for the focus. So at the end you just need to add data-bs-focus="false" to your modal definition. ... | 3 | 4 |
73,967,640 | 2022-10-6 | https://stackoverflow.com/questions/73967640/how-to-activate-existing-python-environment-with-r-reticulate | I have the following existing Python environments: $ conda info --envs base * /home/ubuntu/anaconda3 tensorflow2_latest_p37 /home/ubuntu/anaconda3/envs/tensorflow2_latest_p37 What I want to do is to activate tensorflow2_latest_p37 environment and use it in R code. I tried the following code: library(reticulate) use_co... | I found the most reliable way is to set the RETICULATE_PYTHON system variable before running library(reticulate), since this will load the default environment and changing environments seems to be a bit of an issue. So you should try something like this: library(tidyverse) py_bin <- reticulate::conda_list() %>% filter(... | 3 | 4 |
74,015,280 | 2022-10-10 | https://stackoverflow.com/questions/74015280/pipreqs-not-including-all-packages | I currently have a conda environment tf_gpu and I pip installed pipreqs in it to auto generate requirements.txt Now, in my project folder, I have app.py with the imports : import os from dotenv import load_dotenv from flask import Flask, request from predict import get_recs import urllib.request Also, predict uses pan... | According to the open issues in the GitHub repo, some packages don't map well. You could try opening an issue for this package. | 4 | 4 |
73,965,176 | 2022-10-5 | https://stackoverflow.com/questions/73965176/authenticating-firebase-connection-in-github-action | Background I have a Python script that reads data from an Excel file and uploads each row as a separate document to a collection in Firestore. I want this script to run when I push a new version of the Excel file to GitHub. Setup I placed the necessary credentials in GitHub repo secrets and setup the following workflow... | After hours of research, I found an easy way to store the Firestore service account JSON as a Github Secret. Step 1 : Convert your service account JSON to base-64 Let's name the base-64 encoded JSON SERVICE_ACCOUNT_KEY. There are two ways to get this value: Method 1 : Using command line cat path-to-your-service-account... | 3 | 5 |
74,016,277 | 2022-10-10 | https://stackoverflow.com/questions/74016277/accuracy-while-learning-mnist-database-is-very-low-0-2 | I am developing my ANN from scratch which is supposed to classify MNIST database of handwritten digits (0-9). My feed-forward fully connected ANN has to be composed of: One input layer, with 28x28 = 784 nodes (that is, features of each image) One hidden layer, with any number of neurons (shallow network) One output la... | Combining the changes you and other mentionned, I was able to have it work. See this gist: https://gist.github.com/theevann/77bb863ef260fe633e3e99f68868f116/revisions Changes made: Use a uniform initialisation (critical) Use relu activation (critical) Use more hidden layers (critical) Comment your SGD momentum as it s... | 6 | 2 |
74,023,492 | 2022-10-11 | https://stackoverflow.com/questions/74023492/netsuite-rest-api-returns-no-content-status-204-when-completed-successfully | i use the requests library. how can this be the default behavior? any way to return the ID of the item created? def create_sales_order(): url = f"https://{url_account}.suitetalk.api.netsuite.com/services/rest/record/v1/salesOrder" data = { "entity": { "id": "000" }, "item": { "items": [ { "item": { "id": 25 }, "quantit... | Ok so it turns out that the header returned in the 204 empty response contains a link to the created item (Location is the key name in the json returned) , which is sufficient to do another get request and have all the info returned. | 3 | 4 |
73,961,938 | 2022-10-5 | https://stackoverflow.com/questions/73961938/flask-sqlalchemy-db-create-all-raises-runtimeerror-working-outside-of-applicat | I recently updated Flask-SQLAlchemy, and now db.create_all is raising RuntimeError: working outside of application context. How do I call create_all? from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///project.db' db = SQLAlchemy(app) ... | As of Flask-SQLAlchemy 3.0, all access to db.engine (and db.session) requires an active Flask application context. db.create_all uses db.engine, so it requires an app context. with app.app_context(): db.create_all() When Flask handles requests or runs CLI commands, a context is automatically pushed. You only need to p... | 32 | 82 |
73,997,582 | 2022-10-8 | https://stackoverflow.com/questions/73997582/should-i-repeat-parent-class-init-arguments-in-the-child-classs-init-o | Imagine a base class that you'd like to inherit from: class Shape: def __init__(self, x: float, y: float): self.x = x self.y = y There seem to be two common patterns of handling a parent's kwargs in a child class's __init__ method. You can restate the parent's interface completely: class Circle(Shape): def __init__(se... | If the parent class has required (positional) arguments (as your Shape class does), then I'd argue that you must include those arguments in the __init__ of the child (Circle) for the sake of being able to pass around "shape-like" instances and be sure that a Circle will behave like any other shape. So this would be you... | 27 | 20 |
74,012,595 | 2022-10-10 | https://stackoverflow.com/questions/74012595/why-does-code-that-in-3-10-throws-a-recursionerror-as-expected-not-throw-in-earl | To start I tried this def x(): try: 1/0 # just an division error to get an exception except: x() And this code behaves normally in 3.10 and I get RecursionError: maximum recursion depth exceeded as I expected but 3.8 goes into a stack overflow and doesn't handle the recursion error properly. But I did remember that th... | The different behaviors for 3.10 and other versions seem to be because of a Python issue (python/cpython#86666), you can also see the correct error on Python 2.7. The print "fixes" things because it makes Python check the recursion limit again, and through a path that is presumably not broken. You can see the code wher... | 10 | 5 |
73,992,417 | 2022-10-7 | https://stackoverflow.com/questions/73992417/itertools-combinations-find-if-a-combination-is-divisible | Given itertools combinations with an r of 4: from itertools import combinations mylist = range(0,35) r = 4 combinationslist = list(combinations(mylist, r)) Which will output: (0, 1, 2, 3) (0, 1, 2, 4) (0, 1, 2, 5) (0, 1, 2, 6) (0, 1, 2, 7) (0, 1, 2, 8) (0, 1, 2, 9) ... (30, 31, 32, 33) (30, 31, 32, 34) (30, 31, 33, 34... | I have authored a package in R called RcppAlgos that has functions specifically for this task. TL;DR Use comboRank from RcppAlgos. Details In the article that @wim linked to, you will see that this procedure is often called ranking and as many have pointed out, this boils down to counting. In the RcppAlgos package ther... | 3 | 2 |
74,032,055 | 2022-10-11 | https://stackoverflow.com/questions/74032055/how-to-verify-if-a-graph-has-crossing-edges-in-networkx | I am creating a genetic algorithm to solve the traveling salesman problem using python and networkx. And I'm adding a condition to converge to a satisfactory solution: the path must not have crossing edges. I wonder if there's a quick function in networkx to verify if the graph has crossing edges or, at least, want to ... | My first reading was the same as @AveragePythonEngineer's. Normally in the travelling salesman problem, and graph theory in general, we don't care too much about the positions of the vertices, only the distances between them. And I thought you might be confusing the drawing of a graph with the graph (it's just one real... | 4 | 7 |
73,975,798 | 2022-10-6 | https://stackoverflow.com/questions/73975798/why-does-asyncio-wait-keep-a-task-with-a-reference-around-despite-exceeding-the | I recently found and reproduced a memory leak caused by the use of asyncio.wait. Specifically, my program periodically executes some function until stop_event is set. I simplified my program to the snippet below (with a reduced timeout to demonstrate the issue better): async def main(): stop_event = asyncio.Event() whi... | The key concept to understand here is that the return value of wait() is a tuple (completed, pending) tasks. The typical way to use wait()-based code is like this: async def main(): stop_event = asyncio.Event() pending = [... add things to wait ...] while pending: completed, pending = await asyncio.wait(pending, timeou... | 7 | 4 |
74,026,454 | 2022-10-11 | https://stackoverflow.com/questions/74026454/julia-spherical-harmonics-different-from-python | I would like to calculate the Spherical Harmonics with Julia. I have done this with the following code: using GSL function radius(x, y, z) return sqrt(x^2 + y^2 + z^2) end function theta(x, y, z) return acos(z / radius(x, y, z)) end function phi(x, y, z) return atan(y, x) end function harmonics(l, m, x, y, z) return (-... | The comment by @Oscar Smith got me started on the solution. Julia uses a different convention for the angles returned by atan, provided two arguments are passed [Julia, Numpy]. If we use atan(y / x) instead of atan(y, x) in Julia we get the same result. | 3 | 3 |
74,031,620 | 2022-10-11 | https://stackoverflow.com/questions/74031620/calculate-the-slope-for-every-n-days-per-group | I have the following dataframe (sample): import pandas as pd data = [['A', '2022-09-01', 2], ['A', '2022-09-02', 1], ['A', '2022-09-04', 3], ['A', '2022-09-06', 2], ['A', '2022-09-07', 1], ['A', '2022-09-07', 2], ['A', '2022-09-08', 4], ['A', '2022-09-09', 2], ['B', '2022-09-01', 2], ['B', '2022-09-03', 4], ['B', '2022... | Solution df['n'] = df.groupby('group').cumcount() // 3 df.merge( df .groupby(['group', 'n']) .apply(lambda s: np.polyfit(s['diff_days'], s['value'], 1)[0]) .reset_index(name='slope') ) How this works? Create a sequential counter per group using cumcount then floor divide by 3 to get blocks of 3 rows Group the datafra... | 3 | 3 |
74,015,708 | 2022-10-10 | https://stackoverflow.com/questions/74015708/why-when-i-send-an-email-via-fastapi-mail-the-email-i-receive-displays-the-same | I am trying to send an email using FastAPI-mail, and even though I am successfully sending it, when I open the email in Gmail or Outlook, the content (message) appears twice. I am looking at the code but I don't think I am attaching the message twice (also note that the top message always shows the tags, while the seco... | Instead of body, use the html property. message = MessageSchema( subject="Fastapi-Mail module", recipients=email.dict().get("email"), # List of recipients, as many as you can pass html=template, # <<<<<<<<< here subtype="html" ) | 3 | 3 |
74,008,146 | 2022-10-9 | https://stackoverflow.com/questions/74008146/bifurcation-diagram-of-dynamical-system | TL:DR How can one implement a bifurcation diagram of a seasonally forced epidemiological model such as SEIR (susceptible, exposed, infected, recovered) in Python? I already know how to implement the model itself and display a sampled time series (see this stackoverflow question), but I am struggling with reproducing a ... | The answer to this questions is here on the Computational Science stack exchange. All credit to Lutz Lehmann. | 5 | 0 |
74,027,060 | 2022-10-11 | https://stackoverflow.com/questions/74027060/specify-separate-sources-for-different-packages-in-pyproject-toml | My project has various private python packages developed internally in my organization. I am using [tool.poetry.source] to specify the PyPi server. I have a use case to specify custom PyPi server url for different packages. This is the content of my pyproject.toml [tool.poetry.dependencies] python = "^3.8" package-a = ... | This is described in the docs: [tool.poetry.dependencies] python = "^3.8" package-a = { version = "0.1.2", source = "internal-repo-1" } package-b = { version = "0.2.1", source = "internal-repo-2" } package-c = { version = "0.4.2", source = "internal-repo-2" } [[tool.poetry.source]] name = "internal-repo-1" url = "https... | 3 | 4 |
74,031,424 | 2022-10-11 | https://stackoverflow.com/questions/74031424/how-to-implement-python-udf-in-dbt | Please I need some help with applying python UDF to run on my dbt models. I successfully created a python function in snowflake (DWH) and ran it against a table. This seems to work as expected, but implementing this on dbt seems to be a struggle. Some advice/help/direction will make my day. here is my python UDF create... | Assuming that UDF already exists in Snowflake: {{ config(materialized = 'view') }} WITH SEC AS( SELECT A."AccountID" AS AccountID, A."AccountName" AS AccountName , A."Password" AS Passwords, {{target.schema}}.sha3_512(A."Password") As SHash FROM {{ ref('Green', 'Account') }} A ) SELECT * FROM SEC; The function could ... | 6 | 6 |
74,028,201 | 2022-10-11 | https://stackoverflow.com/questions/74028201/can-you-plot-multiple-precision-recall-curves-using-precisionrecalldisplay | I am trying to plot Precision Recall curve using PrecisionRecallDisplay from scikit-learn. I have model predicted values in y_pred and actual values in y_true. I can plot precision recall curve using the following syntax: metrics.PrecisionRecallDisplay.from_predictions(y_true, y_pred) But I want to plot multiple curve... | Since sklearn display routines are basically just matplotlib wrappers, the easiest way seems to be utilizing the ax argument, like this: import matplotlib.pyplot as plt fig, ax = plt.subplots() PrecisionRecallDisplay.from_predictions(y_train, y_pred_train, ax=ax) PrecisionRecallDisplay.from_predictions(y_test, y_pred, ... | 4 | 11 |
74,027,350 | 2022-10-11 | https://stackoverflow.com/questions/74027350/python3-permutations-for-7-digit-number-that-totals-to-a-number | I need to find a solution for the below problem in Python3. I tried itertools.combinations but not clear on how to do it. Prepare a 7-digit number that sums to 5. Each digit can be between 0-4 only. Also, there can be repetitions. Valid example numbers are - [ [2,1,1,0,0,1,0], [3,0,1,0,0,1,0], [0,0,0,4,0,0,1], [1,0,0,3... | This function will find every combination, with repeated combinations, that sum to N: from itertools import product from typing import List, Tuple def perm_n_digit_total(n_digits, total, choices) -> List[Tuple]: return list(filter( lambda x: sum(x) == total, product(choices, repeat=n_digits) )) Example: perm_n_digit_t... | 3 | 2 |
74,025,103 | 2022-10-11 | https://stackoverflow.com/questions/74025103/how-to-make-python-for-loops-faster | I have a list of dictionaries, like this: [{'user': '123456', 'db': 'db1', 'size': '8628'} {'user': '123456', 'db': 'db1', 'size': '7168'} {'user': '123456', 'db': 'db1', 'size': '38160'} {'user': '222345', 'db': 'db3', 'size': '8628'} {'user': '222345', 'db': 'db3', 'size': '8628'} {'user': '222345', 'db': 'db5', 'siz... | There are two main issue with the current approach: the inefficient algorithm and the inefficient data structure. The first is that the algorithm used is clearly inefficient as it iterates many times over the big list. There is not need to iterate over the whole list to filter a unique user and db. You can iterate over... | 3 | 3 |
74,019,260 | 2022-10-10 | https://stackoverflow.com/questions/74019260/how-to-specify-dependencies-for-the-entire-router | class User(BaseModel): name: str token: str fake_db = [ User(name='foo', token='a1'), User(name='bar', token='a2') ] async def get_user_by_token(token: str = Header()): for user in fake_db: if user.token == token: return user else: raise HTTPException(status_code=401, detail='Invalid token') @router.get(path='/test_a',... | You can use the dependencies parameter to add global dependencies when creating the router instance: router = APIRouter(dependencies=[Depends(get_user_by_token)]) or, when adding the router to the app instance: app.include_router(router, dependencies=[Depends(get_user_by_token)]) Please have a look at FastAPI's docum... | 3 | 6 |
74,014,379 | 2022-10-10 | https://stackoverflow.com/questions/74014379/how-to-fine-tune-gpt-j-using-huggingface-trainer | I'm attempting to fine-tune gpt-j using the huggingface trainer and failing miserably. I followed the example that references bert, but of course, the gpt-j model isn't exactly like the bert model. The error indicates that the model isn't producing a loss, which is great, except that I have no idea how to make it gener... | I found what appears to work, though now I'm running low on memory and working through ways of handling it. The data_collator parameter seems to take care of the exact issue that I was having. data_collator = DataCollatorForLanguageModeling(tokenizer, mlm=False) trainer = Trainer( model=model, args=training_args, train... | 4 | 1 |
74,020,472 | 2022-10-10 | https://stackoverflow.com/questions/74020472/extract-all-phrases-from-a-pandas-dataframe-based-on-multiple-words-in-list | I have a list, L: L = ['top', 'left', 'behind', 'before', 'right', 'after', 'hand', 'side'] I have a pandas DataFrame, DF: Text the objects are both before and after the person the object is behind the person the object in right is next to top left hand side of person I would like to extract all words i... | Try: df["Extracted_Value"] = ( df.Text.apply( lambda x: "|".join(w if w in L else "" for w in x.split()).strip("|") ) .replace(r"\|{2,}", "_", regex=True) .str.replace("|", " ", regex=False) ) print(df) Prints: Text Extracted_Value 0 the objects are both before and after the person before_after 1 the object is behind... | 3 | 4 |
73,991,675 | 2022-10-7 | https://stackoverflow.com/questions/73991675/on-failure-callback-triggered-multiple-times | I want to publish SINGLE Kafka message in case of airflow PARALLEL task failures. my airflow dags are similar to below. from datetime import datetime, timedelta from airflow.models import Variable from airflow import DAG from airflow.operators.dummy import DummyOperator from airflow.operators.python_operator import Pyt... | You can use trigger_rule + PythonOperator to processing failed tasks. Here is an example: import logging import pendulum from airflow import DAG from airflow.models import TaskInstance from airflow.operators.python import PythonOperator from airflow.utils.state import TaskInstanceState from airflow.utils.trigger_rule i... | 3 | 5 |
73,991,600 | 2022-10-7 | https://stackoverflow.com/questions/73991600/equivalent-of-tf-contrib-legacy-seq2seq-attention-decoder-in-tensorflow-2-after | I have the following code in TensorFlow 1.0. I tried to migrate it to TensorFlow 2.0 using tf_upgrade_v2 script. However, it didnt find an equivalent function in the tf-2 compact version. I was recommended to use tensorflow_addons. However, I dont see an equivalent attention_decoder in the tf_addons module. Please guid... | While there is no equivalent in Tensorflow 2.x API, the original implementation can be revised to be compatible with the new API. I have made the conversion below, along with a simple test case to verify it runs successfully. # https://github.com/tensorflow/tensorflow/blob/v1.15.5/tensorflow/contrib/legacy_seq2seq/pyth... | 5 | 3 |
74,015,663 | 2022-10-10 | https://stackoverflow.com/questions/74015663/how-to-plot-axes-with-arrows-in-matplotlib | I want to achieve the following three things: add arrows on x and y axes show only the values that are used add labels for coordinates My code on this moment: x = [9, 8, 11, 11, 14, 13, 16, 14, 14] y = [9, 16, 15, 11, 10, 11, 10, 8, 8] fig = plt.figure(figsize=(7,7), dpi=300) axes = fig.add_axes([0,1,1,1]) axes.set_x... | You can draw arrows by overlaying triangle shaped points over the ends of your spines. You'll need to leverage some transforms, but you can also create your labels by manually adding text to your Axes objects as well. Labelling each coordinate can be done via axes.annotate, but you'll need to manually specify the locat... | 3 | 3 |
74,015,260 | 2022-10-10 | https://stackoverflow.com/questions/74015260/how-to-make-a-list-inside-a-class-static-for-the-entire-program | I'm messing around with classes and data flow and I am having difficulties creating a list of classes inside the class (to give control of the list to the class in itself). class Person: listOfPeople = [] def __init__(self, name, age): self.name = name self.age = age self.listOfPeople = [] def set_age(self, age): if ag... | this code automatically adds new instances to Person.listOfPeople class Person: listOfPeople = [] def __init__(self, name, age): self.name = name self.age = age Person.listOfPeople.append(self) def set_age(self, age): if age <= 0: raise ValueError('The age must be positive') self._age = age def get_age(self): return se... | 4 | 1 |
74,008,953 | 2022-10-9 | https://stackoverflow.com/questions/74008953/trying-to-set-a-superclass-field-in-a-subclass-using-validator | I am trying to set a super-class field in a subclass using validator as follows: Approach 1 from typing import List from pydantic import BaseModel, validator, root_validator class ClassSuper(BaseModel): field1: int = 0 class ClassSub(ClassSuper): field2: List[int] @validator('field1') def validate_field1(cls, v, values... | The reason your Approach 1 does not work is because by default, validators for a field are not called, when the value for that field is not supplied (see docs). Your validate_field1 is never even called. If you add always=True to your @validator, the method is called, even if you don't provide a value for field1. Howev... | 3 | 3 |
74,014,499 | 2022-10-10 | https://stackoverflow.com/questions/74014499/python-remove-element-list-element-with-same-value-at-position | Let's assume I have a list, structured like this with approx 1 million elements: a = [["a","a"],["b","a"],["c","a"],["d","a"],["a","a"],["a","a"]] What is the fastest way to remove all elements from a that have the same value at index 0? The result should be b = [["a","a"],["b","a"],["c","a"],["d","a"]] Is there a fa... | you can use set to keep the record of first element and check if for each sublist first element in this or not. it will took O(1) time compare to O(n) time to your solution to search. >>> a = [["a","a"],["b","a"],["c","a"],["d","a"],["a","a"],["a","a"]] >>> >>> seen = set() >>> new_a = [] >>> for i in a: ... if i[0] no... | 4 | 6 |
74,014,203 | 2022-10-10 | https://stackoverflow.com/questions/74014203/filter-rows-where-dates-are-available-across-all-groups-using-pandas | I have the following dataframe (sample): import pandas as pd data = [['A', '2022-09-01'], ['A', '2022-09-03'], ['A', '2022-09-07'], ['A', '2022-09-08'], ['B', '2022-09-03'], ['B', '2022-09-07'], ['B', '2022-09-08'], ['B', '2022-09-09'], ['C', '2022-09-01'], ['C', '2022-09-03'], ['C', '2022-09-07'], ['C', '2022-09-10'],... | You can use set operations: # which dates are common to all groups? keep = set.intersection(*df.groupby('group')['date'].agg(set)) # {'2022-09-03', '2022-09-07'} # keep only the matching ones out = df[df['date'].isin(keep)] output: group date 1 A 2022-09-03 2 A 2022-09-07 4 B 2022-09-03 5 B 2022-09-07 9 C 2022-09-03 ... | 4 | 3 |
73,998,994 | 2022-10-8 | https://stackoverflow.com/questions/73998994/python-vscode-importing-from-sibling-directory-without-using-os-paths-append | python 3.8 with VScode. I have two sibling directories, and I want to import the first sibling (support_tools) to the second one. this is my project hierarchy: ├── support_tools │ ├── __init__.py │ └── file_utils.py └── optimizations ├──.vscode │ ├── launch.json │ └── settings.json ├── __init__.py └── test1.py I added... | A simple way is to use the optimizations parent folder as the workspace. VsCode searches files using the workspace as the root directory. If the file you want to import is not in the workspace, it will not find the content. Tips: You can use the absolute path in "python. analytics. extraPaths". Because in the workspac... | 4 | 2 |
74,000,515 | 2022-10-8 | https://stackoverflow.com/questions/74000515/python-unit-testing-how-to-patch-an-async-call-internal-to-the-method-i-am-tes | Im using unittest.mock for building tests for my python code. I have a method that I am trying to test that contains a async call to another function. I want to patch that async call so that I can just have Mock return a testing value for the asset id, and not actually call the async method. I have tried many things I'... | Testing async code is bit tricky. If you are using python3.8 or higher AsyncMock is available. Note: it will work only for Python > 3.8 I think in your case event loop is missing. Here is the code which should work, you may need to do few tweaks. You may also need to install pytest-mock. Having it as fixture will allow... | 7 | 5 |
74,009,559 | 2022-10-10 | https://stackoverflow.com/questions/74009559/dont-drop-unique-value-with-dropna-pandas | what's up? I am having a little problem, where I need to use the pandas dropna function to remove rows from my dataframe. However, I need it to not delete the unique values from my dataframe. Let me explain better. I have the following dataframe: id birthday 0102-2 09/03/2020 0103-2 14/03/2020 0104-2 NaN ... | You could sort by the birthday column and then drop duplicates keeping the first out of the two, by doing the following: The complete code would look like this: import pandas as pd import numpy as np data = { "id": ['102-2','103-2','104-2', '105-2', '105-2', '108-2'], "birthday":['09/03/2020', '14/03/2020', np.nan, np.... | 4 | 4 |
73,992,851 | 2022-10-7 | https://stackoverflow.com/questions/73992851/error-while-opening-ipynb-notebook-in-vscode | I was just writing a python code and after switching folder, it threw an error stating:- Error loading webview: Error: Could not register service workers: InvalidStateError: Failed to register a ServiceWorker: The document is in an invalid state. | Read this issue which can help. Emptying the cache is an effective solution. The simplest step is killall code or restart vscode. | 3 | 9 |
74,008,101 | 2022-10-9 | https://stackoverflow.com/questions/74008101/flask-how-to-specify-a-default-value-for-select-tag-html | I have an app that tracks truck appointments. In this app I have a list of carriers in a db table. When the user wants to update an appointment, they can choose a new carrier from the list of carriers in the db using a dropdown menu. How can I set the dropdown default value to be the current carrier selection? Here's w... | You can add a check if the value is equal to the selected value in the for loop in update.html: update.html: <h4>Current carrier: {{ appt.carrier }}</h4> <label>Option to select a new carrier:</label><br> <select name="carrier"> {% for carrier in carriers %} <option value = "{{ carrier.carrier_name }}" {% if carrier.ca... | 4 | 4 |
74,007,673 | 2022-10-9 | https://stackoverflow.com/questions/74007673/dash-rangeslider-automatically-rounds-marks | I am using the RangeSlider in Python Dash. This slider is supposed to allow users to select a range of dates to display, somewhere between the minimum and maximum years in the dataset. The issue that I am having is that each mark shows as 2k due to it being automatically rounded. The years range between 1784 and 2020, ... | You can use attribute marks to style the ticks of the sliders as follows: marks={i: '{}'.format(i) for i in range(1784,2021,10)} The full code: from dash import Dash, dcc, html app = Dash(__name__) app.layout = html.Div([ dcc.RangeSlider(1784, 2020, id='non-linear-range-slider', marks={i: '{}'.format(i) for i in range... | 4 | 2 |
74,005,380 | 2022-10-9 | https://stackoverflow.com/questions/74005380/how-to-get-all-combinations-of-n-binary-values-where-number-of-1s-are-equal-to | I want to find a list of all possible combinations of 0's and 1's. The only condition is that the number of 1's must be more than or equal to the number of 0's. For example for n = 4 the output should be something like this: [(0, 0, 1, 1), (0, 1, 0, 1), (0, 1, 1, 0), (0, 1, 1, 1), (1, 0, 0, 1), (1, 0, 1, 0), (1, 0, 1, ... | You can use distinct_permutations: from more_itertools import distinct_permutations def get_combos(n): for i in range((n+1)//2, n + 1): for permutation in distinct_permutations([1] * i + [0] * (n - i), n): yield permutation print(list(get_combos(4))) # [(0, 0, 1, 1), (0, 1, 0, 1), (0, 1, 1, 0), (1, 0, 0, 1), (1, 0, 1, ... | 4 | 6 |
74,004,525 | 2022-10-9 | https://stackoverflow.com/questions/74004525/adding-spaces-between-words-evenly-from-left-to-right-untill-a-certain-length | Receiving a string that has 2 or more words and a certain length, I need to insert spaces uniformly between words, adding additional spaces between words from left to right. Let's say I receive "Hello I'm John" and a length of 17, it should return:'Hello I'm John I have tried many different ways and I couldn't do the l... | Probably something like this? words = cad_carateres.split() total_nb_of_spaces_to_add = total_string_length - len(cad_carateres) nb_of_spaces_to_add_list = [total_nb_of_spaces_to_add // (len(words) - 1) + int(i < (total_nb_of_spaces_to_add % (len(words) - 1))) for i in range(len(words) - 1)] + [0] result = ' '.join([w ... | 3 | 4 |
74,003,752 | 2022-10-9 | https://stackoverflow.com/questions/74003752/expected-type-iterable-matched-generic-type-iterablesupportslessthant | @dataclass(frozen=True, eq=True, order=True) class C: x: int l = [C(1), C(2), C(1)] print(sorted(l)) The above code works but gives a warning: Expected type 'Iterable' (matched generic type 'Iterable[SupportsLessThanT]'), got 'list[C]' instead. I think the order=True param passed to @dataclass should result in generat... | Apparently a known bug in PyCharm, tracked here | 4 | 7 |
74,003,276 | 2022-10-9 | https://stackoverflow.com/questions/74003276/python-start-loop-at-row-n-in-a-dataframe | I have this dataframe: a = [0,0,5,0,0,0,0,0,0,7,0,0,0,0,0,0,0,0] b = [0,0,0,0,250,350,500,0,0,0,0,0,0,125,70,95,0,0] df = pd.DataFrame(columns=['a', 'b']) df = pd.DataFrame.assign(df, a=a, b=b) df a b 0 0 0 1 0 0 2 5 0 3 0 0 4 0 250 5 0 350 6 0 500 7 0 0 8 0 0 9 7 0 10 0 0 11 0 0 12 0 0 13 0 125 14 0 70 15 0 95 16 0 0 ... | Another possible solution: df1 = df.mask(df.eq(0)).dropna(how='all') df1.assign(b = df1['b'].shift(-1)).dropna() Output: a b 2 5.0 250.0 9 7.0 125.0 | 3 | 2 |
74,000,594 | 2022-10-8 | https://stackoverflow.com/questions/74000594/why-is-super-not-behaving-like-i-expected-when-assigning-to-a-class-variable-o | I am attempting to experiment with classes so I can better understand what they do. I wanted to build a counter which records the number of instances of a class (MyClass): class ObjectCounter: # I want this to count the number of objects in each class myclass_obj_count = 0 class MyClass(ObjectCounter): def __init__(sel... | First, be aware of the += operator; it's implementation is quite subtle: a += b becomes a = a.__iadd__(b) This perhaps strange definition allows python to support it even for immutable types (like strings). Note what happens when used for a class variable that is referred to by the alias self class ObjectCounter: # I... | 4 | 2 |
73,993,861 | 2022-10-8 | https://stackoverflow.com/questions/73993861/automatic-custom-constructor-for-python-dataclass | I'm trying to create a custom constructor for my python dataclass that will ideally take in a dict (from request json data) and fill in the attributes of the dataclass. Eg @dataclass class SoldItem: title: str purchase_price: float shipping_price: float order_data: datetime def main(): json = requests.get(URL).json() s... | For the simplest approach - with no additional libraries - I would personally go with a de-structuring approach via **kwargs. For example: >>> json = {'title': 'test', 'purchase_price': 1.2, 'shipping_price': 42, 'order_data': datetime.min} >>> SoldItem(**json) SoldItem(title='test', purchase_price=1.2, shipping_price=... | 4 | 5 |
73,997,410 | 2022-10-8 | https://stackoverflow.com/questions/73997410/plotly-python-how-to-change-the-background-color-for-title-text | I'm trying to change the background colour for the title in plotly to something like the below: Plotly Code: from plotly.subplots import make_subplots import plotly.graph_objects as go fig = make_subplots( rows=2, cols=2, subplot_titles=("Plot 1", "Plot 2", "Plot 3", "Plot 4")) fig.add_trace(go.Scatter(x=[1, 2, 3], y=... | From what I can see, there does not seem to be a direct way to set the subplot title backgrounds, however, the closest I could get to what you were looking for was to create an annotation at the top of each chart, and set it's background accordingly. Now you could perhaps generate some form of formula to calculate the... | 3 | 4 |
73,991,085 | 2022-10-7 | https://stackoverflow.com/questions/73991085/pandas-groupby-headn-where-n-is-a-function-of-group-label | I have a dataframe, and I would like to group by a column and take the head of each group, but I want the depth of the head to be defined by a function of the group label. If it weren't for the variable group sizes, I could easily do df.groupby('label').head(n). I can imagine a solution that involves iterating through ... | I would use a dictionary here and using <group>.name in groupby.apply: depth = {'apple': 1, 'car': 2, 'dog': 3} out = (df.groupby('label', group_keys=False) .apply(lambda g: g.head(depth.get(g.name, 0))) ) NB. if you really need a function, you can do the same with a function call. Make sure to return a value in every... | 4 | 2 |
73,990,548 | 2022-10-7 | https://stackoverflow.com/questions/73990548/how-to-provide-c-version-when-extending-python | I want to make c++ code callable from python. https://docs.python.org/3/extending/ explains how to do this, but does not mention how to specify c++ version. By default distutils calls g++ with a bunch of arguments, however does not provide the version argument. Example of setup.py: from distutils.core import setup, Ext... | You can pass compiler arguments as extra_compile_args so for example module = Extension( "Hello", sources = ["hello.cpp"], extra_compile_args = ["-std=c++20"] ) | 4 | 4 |
73,987,319 | 2022-10-7 | https://stackoverflow.com/questions/73987319/how-to-typehint-dynamic-class-instantiation-like-pydantic-and-dataclass | Both Pydantic and Dataclass can typehint the object creation based on the attributes and their typings, like these examples: from pydantic import BaseModel, PrivateAttr, Field from dataclasses import dataclass # Pydantic way class Person(BaseModel): name : str address : str _valid : bool = PrivateAttr(default=False) #d... | @Daniil Fajnberg is mostly correct, but depending on your type checker you can can use the dataclass_transform(Python 3.11) or __dataclass_transform__ early adopters program decorator. Pylance and Pyright (usually used in VS-Code) at least work with these. You can only mimic the behaviour of dataclasses that way though... | 5 | 5 |
73,984,925 | 2022-10-7 | https://stackoverflow.com/questions/73984925/specify-dependency-version-for-git-repository-in-pyproject-toml | I have a python project with all dependencies and versions managed by pyproject.toml file. One of these dependencies is a git reference: [project] name = 'my_package' version = '1.0.0' dependencies = [ 'my_dependency @ git+https://github.com/some_user/some_repo.git' ] In order to improve version management after some ... | Unfortunately it's not possible. As specified here https://peps.python.org/pep-0508/ or here https://pip.pypa.io/en/stable/reference/requirement-specifiers/, you can't use of version requirements with url based dependencies. Your second approach about using tags is the one you need. | 9 | 5 |
73,983,298 | 2022-10-7 | https://stackoverflow.com/questions/73983298/pydantic-error-wrappers-validationerror-value-is-not-a-valid-list-type-type-e | New to FastAPI Getting a "value is not a valid list (type=type_error.list)" error Whenever I try to return {"posts": post} @router.get('', response_model = List[schemas.PostResponseSchema]) def get_posts(db : Session = Depends(get_db)): print(limit) posts = db.query(models.Post).all() return {"posts" : posts} Althoug... | your response expects to be the list by this line of code of yours: @router.get('', response_model = List[schemas.PostResponseSchema]) but your response return {"posts" : posts} is object. so you have to return posts because it is a list of objects as your response expects. otherwise, if you want to use return {"posts... | 8 | 12 |
73,978,318 | 2022-10-6 | https://stackoverflow.com/questions/73978318/splitting-a-list-on-non-sequential-numbers | I have an ordered list of entities, numbered in a broken sequence: [1, 2, 3, 6, 7, 11, 17, 18, 19] I'd like to break the list where there's a gap, and collect the results in a new list: [[1, 2, 3], [6, 7], [11], [17, 18, 19]] I have the feeling there's a name for what I want to do and probably a nice library function... | Plain itertools.groupby approach: from itertools import groupby lst = [1, 2, 3, 6, 7, 11, 17, 18, 19] out = [] for _, g in groupby(enumerate(lst), lambda x: x[0] - x[1]): out.append([v for _, v in g]) print(out) Prints: [[1, 2, 3], [6, 7], [11], [17, 18, 19]] | 4 | 3 |
73,968,584 | 2022-10-6 | https://stackoverflow.com/questions/73968584/flask-sqlalchemy-db-create-all-got-an-unexpected-keyword-argument-app | I'm following a tutorial for creating a Flask app with Flask-SQLAlchemy. However, it has started raising an error when creating the database. How do I create the database? from flask import Flask from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() def create_app(): app = Flask(__name__) app.config["SQLALCHEMY_DAT... | Flask-SQLAlchemy 3 no longer accepts an app argument to methods like create_all. Instead, it always requires an active Flask application context. db = SQLAlchemy() def create_app(): app = Flask(__name__) app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///project.db" db.init_app(app) from . import models with app.app_co... | 23 | 49 |
73,973,332 | 2022-10-6 | https://stackoverflow.com/questions/73973332/check-if-were-in-a-github-action-travis-ci-circle-ci-etc-testing-environme | I would like to programmatically determine if a particular Python script is run a testing environment such as GitHub action Travis CI Circle CI etc. I realize that this will require some heuristics, but that's good enough for me. Are certain environment variables always set? Is the user name always the same? Etc. | An environment variable is generally set for each CI/CD pipeline tool. The ones I know about: os.getenv("GITHUB_ACTIONS") os.getenv("TRAVIS") os.getenv("CIRCLECI") os.getenv("GITLAB_CI") Will return true in a python script when executed in the respective tool environment. e.g: os.getenv("GITHUB_ACTIONS") == "true" in... | 16 | 30 |
73,973,736 | 2022-10-6 | https://stackoverflow.com/questions/73973736/how-to-use-column-value-as-parameter-in-aggregation-function-in-pandas | Given a certain table of type A B C t r 1 t r 1 n j 2 n j 2 n j 2 I would like to group on A and B and only take the number of rows specified by C So the desired output would be A B C t r 1 n j 2 n j 2 I am trying to achieve that through this function but with no luck df.groupby(['A'... | You can use groupby.cumcount and boolean indexing: out = df[df['C'].gt(df.groupby(['A', 'B']).cumcount())] Or with a classical groupby.apply: (df.groupby(['A', 'B'], sort=False, as_index=False, group_keys=False) .apply(lambda g: g.head(g['C'].iloc[0])) ) output: A B C 0 t r 1 2 n j 2 3 n j 2 Intermediates for the g... | 3 | 5 |
73,955,605 | 2022-10-5 | https://stackoverflow.com/questions/73955605/docker-airflow-error-can-not-perform-a-user-install-user-site-packages-a | GOAL Since 2022 Sept 19 The release of Apache Airflow 2.4.0 Airflow supports ExternalPythonOperator I have asked the main contributors as well and I should be able to add 2 python virtual environments to the base image of Airflow Docker 2.4.1 and be able to rune single tasks inside a DAG. My goal is to use multiple ho... | Dockerfile [CORRECT] FROM apache/airflow:2.4.1-python3.8 # Compulsory to switch parameter ENV PIP_USER=false #python venv setup RUN python3 -m venv /opt/airflow/venv1 # Install dependencies: COPY requirements.txt . # --user <--- WRONG, this is what ENV PIP_USER=false turns off #RUN /opt/airflow/venv1/bin/pip install --... | 3 | 7 |
73,970,233 | 2022-10-6 | https://stackoverflow.com/questions/73970233/reset-pandas-cumsum-when-the-condition-is-not-satisified | I went through different stackoverflow questions and finally posting it because I couldnt solve one of the issues I am facing. I have a dataframe like below A B C group1 group1_c 12 group1 group1_c 12 group1 group1_c 12 group1 group1_c 1 group1 group1_c 12 group1 group1_c 12 I have to match two rows together and whene... | If need count groups per consecutive values of C column use Series.ne with Series.shift and cumulative sum, last use counter by GroupBy.cumcount: df['cumul'] = df.groupby(df['C'].ne(df['C'].shift()).cumsum()).cumcount() print (df) A B C cumul 0 group1 group1_c 12 0 1 group1 group1_c 12 1 2 group1 group1_c 12 2 3 group1... | 3 | 4 |
73,968,566 | 2022-10-6 | https://stackoverflow.com/questions/73968566/with-pydantic-how-can-i-create-my-own-validationerror-reason | it seems impossible to set a regex constraint with a __root__ field like this one: class Cars(BaseModel): __root__: Dict[str, CarData] so, i've resorted to doing it at the endpoint: @app.post("/cars") async def get_cars(cars: Cars = Body(...)): x = cars.json() y = json.loads(x) keys = list(y.keys()) try: if any([re.se... | You can pass your own error string by using raise ValidationError("Wrong data type"). Hope it helps. | 5 | -4 |
73,969,054 | 2022-10-6 | https://stackoverflow.com/questions/73969054/how-to-create-combobox-with-django-model | I want to create something like a combo box with django model, but i don't find any field type to do that. something like this: enter image description here | Simply you can do this in models.py: class Student(models.Model): select_gender = ( ('Male', 'Male'), ('Female', 'Female'), ('Other', 'Other'), ) student_name = models.CharField(max_length=100) student_gender = models.CharField(max_length=8, choices=select_gender) In forms.py file, do this: class StudentForm(forms.Mod... | 3 | 4 |
73,962,994 | 2022-10-5 | https://stackoverflow.com/questions/73962994/binding-data-in-type-dict-is-not-supported | I am trying to write json object into a particular column of my sql table variant_str = response.json() print(con.cursor().execute('INSERT INTO TEST_TABLE (JSON_STR) VALUES (?)', (variant_str,))) Here, the variant_str is of type dict. I get an error that: snowflake.connector.errors.ProgrammingError: 252004: Failed pro... | It is possible to use ? as the placeholder for parameter binding: import snowflake.connector snowflake.connector.paramstyle='qmark' Insert using INSERT INTO ... SELECT PARSE_JSON(...) con.cursor().execute('INSERT INTO TEST_TABLE (JSON_STR) SELECT PARSE_JSON(?)' , (variant_str)) where variant_str is a valid JSON strin... | 3 | 4 |
73,958,381 | 2022-10-5 | https://stackoverflow.com/questions/73958381/this-engine-did-not-provide-a-list-of-tried-templates | Wup, I'm trying to deploy a localhost web using Django but I get the following error: TemplateDoesNotExist at / templates/index.html Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.1.2 Exception Type: TemplateDoesNotExist I was looking tutorials and docs but I didn't found the answer. Here is... | templates/ is the base path you've configured in the settings, so you'll want def index(request): return render(request, 'index.html') Furthermore, TEMPLATE_DIRS hasn't been a thing since Django 1.8 or so, and you're on Django 4.x. See these instructions. | 3 | 5 |
73,933,043 | 2022-10-3 | https://stackoverflow.com/questions/73933043/removing-null-values-on-selected-columns-only-in-polars-dataframe | I am trying to remove null values across a list of selected columns. But it seems that I might have got the with_columns operation not right. What's the right approach if you want to operate the removing only on selected columns? df = pl.DataFrame( { "id": ["NY", "TK", "FD"], "eat2000": [1, None, 3], "eat2001": [-2, No... | polars.col also accepts Regular expressions which is one way to select all columns that start with a specific string. polars.all_horizontal combines all results horizontally (i.e., row-wise) to give a single True/False value per row. df.select( ~pl.all_horizontal(pl.col(r'^eat.*$').is_null()) ) shape: (3, 1) ┌──────... | 8 | 11 |
73,948,502 | 2022-10-4 | https://stackoverflow.com/questions/73948502/take-cumsum-of-each-row-in-polars | E.g. if I have import polars as pl df = pl.DataFrame({'a': [1,2,3], 'b': [4,5,6]}) how would I find the cumulative sum of each row? Expected output: a b 0 1 5 1 2 7 2 3 9 Here's the equivalent in pandas: >>> import pandas as pd >>> pd.DataFrame({'a': [1,2,3], 'b': [4,5,6]}).cumsum(axis=1) a b 0 1 5 1 2 7 2 3 9 but ... | cum_sum_horizontal() generates a struct of cum_sum values. df.select(pl.cum_sum_horizontal(pl.all())) shape: (3, 1) ┌───────────┐ │ cum_sum │ │ --- │ │ struct[2] │ ╞═══════════╡ │ {1,5} │ │ {2,7} │ │ {3,9} │ └───────────┘ Which you can unnest() df.select(pl.cum_sum_horizontal(pl.all())).unnest('cum_sum') shape: (3, ... | 3 | 9 |
73,917,061 | 2022-10-1 | https://stackoverflow.com/questions/73917061/how-to-do-a-horizontal-forward-fill-in-polars | I am wondering if there's a way to do forward filling by columns in polars. df = pl.DataFrame( { "id": ["NY", "TK", "FD"], "eat2000": [1, 6, 3], "eat2001": [-2, None, 4], "eat2002": [None, None, None], "eat2003": [-9, 3, 8], "eat2004": [None, None, 8] } ); df shape: (3, 6) ┌─────┬─────────┬─────────┬─────────┬────────... | You can use the new coalesce Expression to fold columns horizontally. If you place the coalesce expressions in a with_columns context, they will be run in parallel. ( df .with_columns(pl.col("^eat.*$").cast(pl.Int64)) .with_columns( pl.coalesce("eat2004", "eat2003", "eat2002", "eat2001", "eat2000"), pl.coalesce("eat200... | 4 | 3 |
73,908,734 | 2022-9-30 | https://stackoverflow.com/questions/73908734/how-to-run-uvicorn-fastapi-server-as-a-module-from-another-python-file | I want to run FastAPI server using Uvicorn from A different Python file. uvicornmodule/main.py import uvicorn import webbrowser from fastapi import FastAPI from fastapi.responses import FileResponse from fastapi.staticfiles import StaticFiles app = FastAPI() import os script_dir = os.path.dirname(__file__) st_abs_file_... | When spawning new processes from the main process (as this is what happens when uvicorn.run() is called), it is important to protect the entry point to avoid recursive spawning of subprocesses, etc. As described in this article: If the entry point was not protected with an if-statement idiom checking for the top-level... | 6 | 8 |
73,914,566 | 2022-9-30 | https://stackoverflow.com/questions/73914566/how-to-properly-suppress-mypy-error-name-qualname-not-defined | When using __qualname__ as part of the python logger formatter for classes, I am getting mypy error 'Name "qualname" not defined'. I can suppress it with inline # type: ignore, but wonder if there are more proper ways to do this, or if there are ways to have mypy recognize __qualname__. | The issue linked by @SilvioMayolo and its duplicate were closed in October 2023 as completed. __qualname__ (and __module__, for that matter) can now be used as-is in class bodies: (playground) class C: foo: ClassVar[str] = __qualname__ + 'bar' This has been possible since 1.9.0. | 4 | 0 |
73,879,213 | 2022-9-28 | https://stackoverflow.com/questions/73879213/instance-is-not-bound-to-a-session | Just like many other people I run into the problem of an instance not being bound to a Session. I have read the SQLAlchemy docs and the top-10 questions here on SO. Unfortunatly I have not found an explanation or solution to my error. My guess is that the commit() closes the session rendering the object unbound. Does t... | ORM entities are expired when committed. By default, if an entity attribute is accessed after expiry, the session emits a SELECT to get the current value from the database. In this case, the session only exists in the scope of the add method, so subsequent attribute access raises the "not bound to a session" error. The... | 4 | 11 |
73,877,870 | 2022-9-28 | https://stackoverflow.com/questions/73877870/can-i-resolve-environment-variables-with-pathlib-path-without-os-path-expandvars | Is there a clean way to resolve environment variables or %VARIABLES% in general purely with the Path class without having to use a fallback solution like os.path.expandvars or "my/path/%variable%".fortmat(**os.environ)? The question How to use win environment variable "pathlib" to save files? doesn't provide an answer.... | This comment from an answer of the linked thread clearly states that it does not provide anything equivalent to os.path.expandvars. Going through the documentation for the module (as of Python 3.10) does not make any references to environment variables. This issue on the CPython issue tracker was closed under the same ... | 6 | 6 |
73,892,881 | 2022-9-29 | https://stackoverflow.com/questions/73892881/error-fail-to-create-pixmap-with-tk-getpixmap-in-tkimgphotoinstancesetsize-wh | When i executing this function i get this error: Fail to create pixmap with Tk_GetPixmap in TkImgPhotoInstanceSetSize. This error occur in this line: fig, ax = plt.subplots()(line 12). The strange thing is, that this error only occur sometimes (Maybe only 10% of their executes). Here is my whole function: from bs4 impo... | This seems to be a memory issue from this issue, new in Matplotlib 3.5 (vs 3.3) The recommended way is to switch to 'Agg' backend if possible [EDIT] Issue is now resolved with default backend in newer versions of Matplotlib: 3.6 (sept 2022), 3.7... If possible, as per wisbucky answer you may upgrade lib: pip install --... | 4 | 2 |
73,893,871 | 2022-9-29 | https://stackoverflow.com/questions/73893871/interactive-brokers-unable-to-fetch-forex-historical-data | I am trying IB very the first time. I am trying to fetch historical data of $EUR but I am getting an error: Error 162, reqId 3: Historical Market Data Service error message:No historical market data for EUR/CASH@FXSUBPIP Last 1800, contract: Contract(secType='CASH', symbol='EUR', exchange='IDEALPRO', currency='USD') ... | The issue here is not on the definition of the FOREX contract itself, but the bar settings requested. durationStr='100 D', barSizeSetting='30 mins', The barSizeSetting is not available for the durationStr selected. If you check the TWS GUI and pull the historical data chart for the FX contract you'll see the lowest ... | 3 | 1 |
73,948,109 | 2022-10-4 | https://stackoverflow.com/questions/73948109/pandas-read-csv-file-error-unicodedecodeerror-utf-8-codec-cant-decode-byte-0 | I would like to open csv data but keep getting the same error, what can I do to succesfully open csv files using Python? #Reading in the files import pandas as pd data1 = pd.read_csv("data1.csv") UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte | byte 0xff in position 0 means that your .csv is probably encoded in utf-16. Try this : data1 = pd.read_csv("data1.csv", encoding="utf-16") | 10 | 17 |
73,951,746 | 2022-10-4 | https://stackoverflow.com/questions/73951746/how-to-use-contextlib-contextmanager-with-a-classmethod | See the below Python 3.10 snippet: import contextlib class Foo: @contextlib.contextmanager @classmethod def state(cls): try: yield finally: pass with Foo.state(): pass It throws a TypeError: Traceback (most recent call last): File "/path/to/code/play/quick_play.py", line 12, in <module> with Foo.state(): File "/path/t... | This should work: import contextlib class Foo: @classmethod @contextlib.contextmanager def state(cls): try: print("A") yield print("C") finally: pass with Foo.state(): print("B") This prints A B C. | 8 | 11 |
73,906,943 | 2022-9-30 | https://stackoverflow.com/questions/73906943/dash-app-cannot-find-pages-folder-when-deploying-on-gcp-using-gunicorn | I am trying to deploy my dash app which uses dash_extensions, Dash_proxy and has multiple pages in the pages folder on GCP cloud run using gunicorn but the app cannot find the pages folder. It works perfectly fine when I use the development server but breaks in the production server because it cannot find the folder pa... | Yes I did. Just had to specify the root folder. This is what I did and it seems to work for me. pages_folder=os.path.join(os.path.dirname(__name__), "pages") app = DashProxy(__name__,use_pages=True, pages_folder=pages_folder, external_stylesheets=[dbc.themes.SIMPLEX]) server=app.server | 5 | 1 |
73,894,238 | 2022-9-29 | https://stackoverflow.com/questions/73894238/gevent-21-12-0-installation-failing-in-mac-os-monterey | I am trying to install gevent 21.12.0 on Mac OS Monterey (version 12.6) with python 3.9.6 and pip 21.3.1. But it is failing with the below error. Any suggestion? (venv) debrajmanna@debrajmanna-DX6QR261G3 qa % pip install gevent Collecting gevent Using cached gevent-21.12.0.tar.gz (6.2 MB) Installing build dependencies ... | Looked all over trying to figure out a solution to this problem until I finally stumbled on this post. I think the issue is specific to the virtual environment. I had the project open with it's own venv in PyCharm, and it seems that the python distribution headers were not findable. To reiterate the solution linked: F... | 6 | 0 |
73,947,300 | 2022-10-4 | https://stackoverflow.com/questions/73947300/pycharm-doesnt-recognize-file-or-folder-with-remote-interpreter | In a file whose only content is def test_sanity(): pass I am trying to run the file, named test_something.py. The folder structure is uv_metadata |---uv_metadata |------tests |----------test_something.py Getting the error ssh://noam.s@ML:2202/home/noam.s/src/uv_metadata/venv/bin/python -u /home/noam.s/.pycharm_helper... | PyCharm 2021.2.3 has a buggy deployment configuration, which can cause clashes and sometimes not work properly when some mappings are configured separately on the same interpreter, even from different projects. Likely, I was using the same interpreter with a different mapping, from some other Pycharm instance. I had to... | 3 | 5 |
73,925,578 | 2022-10-2 | https://stackoverflow.com/questions/73925578/pyautogui-was-unable-to-import-pyscreeze | my code: import pyautogui from time import sleep x, y = pyautogui.locateOnScreen("slorixsh.png", confidence=0.5) error: Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> x, y = pyautogui.locateOnScreen("slorixsh.png", confidence=0.5) File "C:\Users\mrnug\AppData\Local\Programs\Python\Python310... | Yeah, you can fix it by this pip install pyscreeze import pyscreeze import time time.sleep(5) x, y = pyscreeze.locateOnScreen("slorixsh.png", confidence=0.5) | 4 | 8 |
73,890,417 | 2022-9-29 | https://stackoverflow.com/questions/73890417/working-on-new-version-of-psycopg-3-and-while-installing-psycopgc-it-wont-inst | I am working on psycopg 3 and not 2. Here is my code that I am trying to work on: from fastapi import FastAPI, Response, status, HTTPException from fastapi.params import Body from pydantic import BaseModel from typing import Optional from random import randrange import psycopg import psycopg2 from psycopg2.extras impor... | There are 3 ways of installing psycopg 3: Binary installation This method will install a self-contained package with all the libraries required to connect python to your Postgres database. Install packages by running: pip install "psycopg[binary]" Local installation To use psycopg for a production site, this is th... | 4 | 4 |
73,900,006 | 2022-9-29 | https://stackoverflow.com/questions/73900006/best-directory-structure-for-a-repository-with-several-python-entry-points-and-i | I'm working on a project with the following directory structure: project/ package1/ module1.py module2.py package2/ module1.py module2.py main1.py main2.py main3.py ... mainN.py where each mainX.py file is an executable Python script that imports modules from either package1, package2, or both. package1 and package2 a... | The standard solution is to use console_scripts packaging for your entry points - read about the entry-points specification here. This feature can be used to generate script wrappers like main1.py ... mainN.py at installation time. Since these script wrappers are generated code, they do not exist in the project source ... | 6 | 4 |
73,917,887 | 2022-10-1 | https://stackoverflow.com/questions/73917887/firebase-credentials-as-python-environment-variables-could-not-deserialize-key | I'm developing a Python web app with a Firestore realtime database using the firebase_admin library. The Firestore key comes in form of a .json file containing 10 variables. However, I want to store some of these variables as environment variables so they are not visible publicly. So, I don't use a Firebase SDK .json f... | I HAVE SOLVED THE PROBLEM: To solve the problem with "\n" I had to replace the raw string "\n" with "\n", as (presumably) the environment variables return a raw string, which treats backslash () as a literal character. The solution looks as follows: my_credentials = { "type": "service_account", "project_id": "bookclub-... | 7 | 14 |
73,913,522 | 2022-9-30 | https://stackoverflow.com/questions/73913522/why-dont-the-images-align-when-concatenating-two-data-sets-in-pytorch-using-tor | I wanted to concatenate multiple data sets where the labels are disjoint (so don't share labels). I did: class ConcatDataset(Dataset): """ ref: https://discuss.pytorch.org/t/concat-image-datasets-with-different-size-and-number-of-channels/36362/12 """ def __init__(self, datasets: list[Dataset]): """ """ # I think conca... | Corrected code can be found here https://github.com/brando90/ultimate-utils/blob/master/ultimate-utils-proj-src/uutils/torch_uu/dataset/concate_dataset.py you can pip install the library pip install ultimate-utils. Since only links is not a good way to answer I will copy paste the code too with it's test and expected o... | 3 | 1 |
73,953,744 | 2022-10-4 | https://stackoverflow.com/questions/73953744/how-to-test-kfp-components-with-pytest | I'm trying to local test a kubeflow component from kfp.v2.ds1 (which works on a pipeline) using pytest, but struggling with the input/output arguments together with fixtures. Here is a code example to illustrate the issue: First, I created a fixture to mock a dataset. This fixture is also a kubeflow component. # ./fixt... | After spending my afternoon on this, I finally figured out a way to pytest a python-based KFP component. As I found no other lead on this subject, I hope this can help: Access the function to test The trick is not to directly test the KFP component created by the @component decorator. However you can access the inner d... | 3 | 12 |
73,902,642 | 2022-9-29 | https://stackoverflow.com/questions/73902642/office-365-imap-authentication-via-oauth2-and-python-msal-library | I'm trying to upgrade a legacy mail bot to authenticate via Oauth2 instead of Basic authentication, as it's now deprecated two days from now. The document states applications can retain their original logic, while swapping out only the authentication bit Application developers who have built apps that send, read, or o... | The imaplib.IMAP4.error: AUTHENTICATE failed Error occured because one point in the documentation is not that clear. When setting up the the Service Principal via Powershell you need to enter the App-ID and an Object-ID. Many people will think, it is the Object-ID you see on the overview page of the registered App, but... | 22 | 6 |
73,950,834 | 2022-10-4 | https://stackoverflow.com/questions/73950834/zx81-basic-to-pygame-conversion-of-dropout-game | I based the code below on this article: http://kevman3d.blogspot.com/2015/07/basic-games-in-python-1982-would-be.html and on the ZX BASIC in this image: 10 LET P=0 20 LET T=P 30 FOR Z=1 T0 10 35 CLS 37 PRINT AT 12,0;T 40 LET R=INT (RND*17) 50 FOR Y=0 TO 10 60 PRINT AT Y,R;"O" 70 LET N=P(INKEY$="4")-(INKEY$="1") 80 IF... | Here's my reorganisation of your code: import pygame import random # Define global constants TEXT_SIZE = 16 SCREEN_SIZE = (16 * TEXT_SIZE, 13 * TEXT_SIZE) NUM_ROUNDS = 5 def print_at_pos(row_num, col_num, item): """Blits text to row, col position.""" screen.blit(item, (col_num * TEXT_SIZE, row_num * TEXT_SIZE)) # Set u... | 3 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.