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
72,112,776
2022-5-4
https://stackoverflow.com/questions/72112776/shap-value-plotting-error-on-databricks-but-works-locally
I want to do a simple shap analysis and plot a shap.force_plot. I noticed that it works without any issues locally in a .ipynb file, but fails on Databricks with the following error message: Visualization omitted, Javascript library not loaded! Have you run `initjs()` in this notebook? If this notebook was from another...
Let's try slightly different (matplotlib=True): import xgboost import shap X, y = shap.datasets.boston() bst = xgboost.train({"learning_rate": 0.01}, xgboost.DMatrix(X, label=y), 100) explainer = shap.TreeExplainer(bst) shap_values = explainer.shap_values(X) shap.force_plot( explainer.expected_value, shap_values[0,:], ...
5
23
72,162,458
2022-5-8
https://stackoverflow.com/questions/72162458/how-to-refer-to-self-in-pandas-subsetting
When I'm exploring data in an ad hoc way, I often have code like this: X = (adj_all.o.diff(1) / adj_none.o.diff(1)).diff(1) print(X[X > 0]) Is there a way to do this in a single line in an easy way? The following works but is verbose: (adj_all.o.diff(1) / adj_none.o.diff(1)).diff(1)[(adj_all.o.diff(1) / adj_none.o.dif...
You can use pipe: (adj_all.o.diff(1) / adj_none.o.diff(1)).diff(1).pipe(lambda x: x[x>0])
4
4
72,160,981
2022-5-8
https://stackoverflow.com/questions/72160981/how-to-make-a-csv-row-for-each-2-lines-in-a-txt-file
I have a text file like this: Viruses/GCF_000820355.1_ViralMultiSegProj14361_genomic.fna.gz Sclerophthora macrospora virus A Viruses/GCF_000820495.2_ViralMultiSegProj14656_genomic.fna.gz Influenza B virus RNA Viruses/GCF_000837105.1_ViralMultiSegProj14079_genomic.fna.gz Tomato mottle virus And I need to get a csv file...
Using any awk in any shell on every Unix box and only storing 1 line at a time in memory so it'll work no matter how large your input file is: $ awk '{ORS=(NR%2 ? "," : RS)} 1' file Viruses/GCF_000820355.1_ViralMultiSegProj14361_genomic.fna.gz,Sclerophthora macrospora virus A Viruses/GCF_000820495.2_ViralMultiSegProj14...
4
5
72,156,580
2022-5-7
https://stackoverflow.com/questions/72156580/azure-databricks-error-with-custom-library-on-cluster-in-vnet
We are using Azure Databricks with a single-node cluster in a VNet (Runtime Version 10.4 LTS). We also need to use a custom/private python module (wheel). After the library is installed on the cluster, everything is working fine, but after the cluster is restarted and the library installed, the following error appears ...
You need to make sure that you have configure Network Security Group rules according to documentation, specifically that you don't block traffic on port 3306. You also need to check that your user-defined routes or firewall are configured correctly and don't block outgoing traffic to the built-in Hive metastore - the h...
5
2
72,156,750
2022-5-7
https://stackoverflow.com/questions/72156750/telegram-bot-to-send-auto-message-every-n-hours-with-python-telegram-bot
I am quite new in building bots so I created a very simple Telegram bot and it works great but can't figure out how to make the bot send messages every n minutes or n hours when /start_auto command is initiated. I made a workaround with while loop but it looks stupid and during the loop users won't be able to interact ...
will post a solution which I found: def callback_auto_message(context): context.bot.send_message(chat_id='12345678', text='Automatic message!') def start_auto_messaging(update, context): chat_id = update.message.chat_id context.job_queue.run_repeating(callback_auto_message, 10, context=chat_id, name=str(chat_id)) # con...
5
6
72,155,476
2022-5-7
https://stackoverflow.com/questions/72155476/is-this-greedy-behavior-of-lists-guaranteed
I occasionally use the "trick" to extend a list by a mapped version of itself, for example to efficiently compute powers of 2: from operator import mul powers = [1] powers += map(mul, [2] * 10, powers) print(powers) # prints [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024] This relies on the += immediately appending each...
I don't see any tests or docs that the greedy behavior is guaranteed; however, I do think it is the expected behavior and that code in the wild relies on it. FWIW, += with lists is equivalent to list.extend(), so your "trick" boils down to: >>> powers = [1] >>> powers.extend(2*x for x in islice(powers, 10)) >>> powers ...
15
7
72,151,781
2022-5-7
https://stackoverflow.com/questions/72151781/how-can-i-get-a-raspberry-pi-pico-to-communicate-with-a-pc-external-devices
For example when I give 5 to the code, I want to turn on the LED in our RPi pico (connected to a PC via a cable). #This code will run in my computer (test.py) x=int(input("Number?")) if (x==5): #turn on raspberry pi pico led The code of the RPi pico: #This code will run in my rpi pico (pico.py) from machine import Pin...
A simple method of communicating between the host and the Pico is to use the serial port. I have a rp2040-zero, which presents itself to the host as /dev/ttyACM0. If I use code like this on the rp2040: import sys import machine led = machine.Pin(24, machine.Pin.OUT) def led_on(): led(1) def led_off(): led(0) while True...
4
11
72,152,748
2022-5-7
https://stackoverflow.com/questions/72152748/time-it-takes-to-square-in-python
I was wondering whether x**2 or x*x is faster def sqr(x): for i in range (20): x = x**2 return x def sqr_(x): for i in range (20): x = x*x return x When I time it, this is what I get: The time it takes for x**2: 101230500 The time it takes for x*x: 201469200 I have tried it many many times, they are either equal, or ...
For small integers, x*x is significantly faster than x**2 since CPython does a lot more operation internally to compute a**b. Actually, on my machine x*x is 4 times faster (processor i5-9600KF, CPython 3.8.1, on Windows). That being said, in you code, numbers grows very quickly and Python integers are unbounded. In fac...
6
6
72,145,492
2022-5-6
https://stackoverflow.com/questions/72145492/conda-init-without-closing-the-current-shell
There are a number of use cases for which I am trying to use conda . The main headache is that conda init just does not want to play fair within the flow of a script in the same bash shell. I frequently see CommandNotFoundError: Your shell has not been properly configured to use 'conda activate'. That happens even th...
Generally, one should not need to "activate" an environment when working programmatically. That's what conda run is for... conda run -n py38 python my_script.py Otherwise, if CONDA_DIR is defined, then the following would run the initialization shell commands in an active bash session: eval "$(${CONDA_DIR}/bin/conda s...
5
7
72,144,371
2022-5-6
https://stackoverflow.com/questions/72144371/how-to-fix-tiktok-selenium-robot-detection
How to fix TikTok selenium robot detection Background-Info I'm creating a python selenium bot to do things on the TikTok website. The user will log in manually so the website detecting mouse movement and typing speed is irrelevant.The issue is, is that I can't log in while using selenium What I've tried I've tried l...
A few things that might help: Make sure your proxy is changing during every login attempt. For every instance of a new login create a new webdriver environment either with the same proxy or a new one. Add random wait times. For example instagram will restrict accounts that they suspect of botting. To fix this one so...
4
2
72,140,531
2022-5-6
https://stackoverflow.com/questions/72140531/flatten-xml-data-as-a-pandas-dataframe
How can I convert this XML file at this address into a pandas dataframe? I have downloaded the XML as a file and called it '058com.xml' and run the code below, though the last column of the resulting dataframe is a mess of data arranged as multiple OrderedDict. The XML structure seems complex and is beyond my knowledge...
Since the URL really contains two data sections under each <Tour>, specifically <Mentions> (which appear to be aggregate vote data) and <Candidats> (which are granular person-level data) (pardon my French), consider building two separate data frames using the new IO method, pandas.read_xml, which supports XSLT 1.0 (via...
4
1
72,138,544
2022-5-6
https://stackoverflow.com/questions/72138544/pandas-calculate-difference-between-a-row-and-all-other-rows-and-create-column
We have data as below Name value1 Value2 finallist 0 cosmos 10 20 [10,20] 1 network 30 40 [30,40] 2 unab 20 40 [20,40] is there any way to do difference between all the rows Something final output like Name value1 Value2 finallist cosmos network unab 0 cosmos 10 20 [10,20] 0 40 30 1 network 30 40 [30,40] 40 0 10 2 u...
You want the pairwise absolute difference of the sum of the values for each row. The easiest might be to use the underlying numpy array. absolute difference of the sum of the "value" columns # get sum of values per row and convert to numpy array a = df['value1'].filter(regex='(?i)value').sum(1).to_numpy() # compute the...
5
4
72,137,740
2022-5-6
https://stackoverflow.com/questions/72137740/how-to-replicate-pandas-dataframe-rows-and-change-periodically-one-column
I have df going like pd.DataFrame([["A1" "B1", "C1", "P"], ["A2" "B2", "C2", "P"], ["A3" "B3", "C3", "P"]], columns=["col_a" "col_b", "col_c", "col_d"]) col_a col_b col_c col_d A1 B1 C1 P A2 B2 C2 P A3 B3 C3 P ... the result I need is basically repeat and ensure that columns have P Q R extension in col_d for every uni...
Add values to column col_d by DataFrame.assign with numpy.tile: L = ['P','Q','R'] new_df = (pd.DataFrame(np.repeat(df.values, 3, axis=0), columns=df.columns) .assign(col_d = np.tile(L, len(df)))) print (new_df) col_acol_b col_c col_d 0 A1B1 C1 P 1 A1B1 C1 Q 2 A1B1 C1 R 3 A2B2 C2 P 4 A2B2 C2 Q 5 A2B2 C2 R 6 A3B3 C3 P 7 ...
4
3
72,134,364
2022-5-5
https://stackoverflow.com/questions/72134364/aiflow-2-xcom-in-task-groups
I have two tasks inside a TaskGroup that need to pull xcom values to supply the job_flow_id and step_id. Here's the code: with TaskGroup('execute_my_steps') as execute_my_steps: config = {some dictionary} dependencies = {another dictionary} task_id = 'execute_spark_job_step' task_name = 'spark_job' add_step = EmrAddSt...
TL;DR: Your issue is happening because the id is not task_id it's group_id.task_id so your code should be: task_ids=f"execute_my_steps.{ task_id }" => step_id="{{ task_instance.xcom_pull(dag_id='my_dag', task_ids=f"execute_my_steps.{ task_id }", key='return_value') }}", The explanation why it happens: When task is a...
4
10
72,135,183
2022-5-6
https://stackoverflow.com/questions/72135183/how-to-create-a-new-data-frame-by-using-substring-and-matching-column-values-in
Suppose I have a simple dataframe where I have four features as food, kitchen, city, and detail. d = {'Food': ['P1|0', 'P2', 'P3|45', 'P1', 'P2', 'P4', 'P1|1', 'P3|7', 'P5', 'P1||23'], 'Kitchen' : ['L1', 'L2','L9', 'L4','L5', 'L6','L1', 'L9','L10', 'L1'], 'City': ['A', 'A', 'A', 'B', 'B','B', 'C', 'C', 'C','D'], 'Detai...
IIUC, you can split each row into two rows by combining the city names to a list and then using explode: merged = df.merge(df, on=["subFood","Kitchen"], suffixes=("_1","_2")).query("City_1 != City_2") merged["City"] = merged[["City_1","City_2"]].to_numpy().tolist() output = merged.drop(["City_1","City_2","Detail_2"],ax...
4
1
72,133,537
2022-5-5
https://stackoverflow.com/questions/72133537/determining-the-validity-of-a-multi-hot-encoding
Suppose I have N items and a multi-hot vector of values {0, 1} that represents inclusion of these items in a result: N = 4 # items 1 and 3 will be included in the result vector = [0, 1, 0, 1] # item 2 will be included in the result vector = [0, 0, 1, 0] I'm also provided a matrix of conflicts which indicates which ite...
TL;DR: you can use Numba to optimize np.dot to only operate only on binary values. More specifically, you can perform SIMD-like operations on 8 bytes at once using 64-bit views. Converting lists to arrays First of all, the lists can be efficiently converted to relatively-compact arrays using this approach: vector = ...
5
1
72,130,023
2022-5-5
https://stackoverflow.com/questions/72130023/numba-parallel-causing-incorrect-results-in-a-for-loop-i-cant-pinpoint-the-iss
So I have what appears to be a perfectly acceptable loop to make parallel. But when I pass it to Numba parallel, it always gives incorrect results. All that happens in the loop is an input matrix has one element set to 0, matrix multiplication occurs and populates a new matrix, then the element that was set to 0 is set...
There is a race condition in numbafunc. Indeed, a[i] = 0 modifies the array a shared between multiple threads reading/writing a for different i values. Storing the value in temp to restore it later only works in sequential, but not in parallel since threads can read a at any time. To solve this issue, each thread shoul...
4
4
72,131,251
2022-5-5
https://stackoverflow.com/questions/72131251/mypy-gives-incompatible-default-for-argument-when-dict-param-defaults-none
I understand that a Dict parameter in a Python function is best set to a default of None. However, mypy seems to disagree: def example(self, mydict: Dict[int, str] = None): return mydict.get(1) This results in the mypy error: error: Incompatible default for argument "synonyms" (default has type "None", argument has t...
I think the type should be "dict or None", so a Union of the two: def example(self, mydict: Union[Dict[int, str], None] = None): return mydict.get(1)
9
10
72,126,748
2022-5-5
https://stackoverflow.com/questions/72126748/what-is-the-difference-between-prophet-package-and-fbprophet-in-python
I googled how to install the fbprophet package, but the top result is how to install prophet. What is the difference between the two packages? Are they the same?
It's by the same devs. Seems it was just a name change. Prophet is on PyPI, so you can use pip to install it. From v0.6 onwards, Python 2 is no longer supported. As of v1.0, the package name on PyPI is "prophet"; prior to v1.0 it was "fbprophet". https://pythonlang.dev/repo/facebook-prophet/
7
8
72,119,316
2022-5-4
https://stackoverflow.com/questions/72119316/generate-jwt-token-signed-with-rsa-key-in-python
I am trying to convert this java code for generating JWT token in python. String privateKeyContent = privateKey .replaceAll(Definitions.ApiGeneral.LINE_BREAKER, "") .replace(Definitions.AuthProperty.PRIVATE_KEY_START, "") .replace(Definitions.AuthProperty.PRIVATE_KEY_END, ""); PKCS8EncodedKeySpec keySpecPKCS8 = new PKC...
The issue is precisely identified in the error message: Your private key is incorrectly formatted. A PEM encoded key consists of the Base64 encoded body, which contains a line break after every 64 characters, and a header and footer on separate lines. Your key is missing the line breaks. load_pem_private_key() expects ...
4
6
72,121,390
2022-5-5
https://stackoverflow.com/questions/72121390/how-to-use-jupyterlab-in-visual-studio-code
is there a way to use JupyterLab in VS Code? I know that VS Code provides the Jupyter Notebook extension. However, I need to connect to another server remotely...... Any guidance will be appreciated!
You can offload intensive computation in a Jupyter Notebook to other computers by connecting to a remote Jupyter server. Once connected, code cells run on the remote server rather than the local computer. To connect to a remote Jupyter server: Select the Jupyter Server: local button in the global Status bar or run the...
8
7
72,118,665
2022-5-4
https://stackoverflow.com/questions/72118665/particle-detection-with-python-opencv
I'm looking for a proper solution how to count particles and measure their sizes in this image: In the end I have to obtain the lists of particles' coordinates and area squares. After some search on the internet I realized there are 3 approaches for particles detection: blobs Contours connectedComponentsWithStats Lo...
Since the particles are in white and the background in black, we can use Kmeans Color Quantization to segment the image into two groups with cluster=2. This will allow us to easily distinguish between particles and the background. Since the particles may be very tiny, we should try to avoid blurring, dilating, or any m...
6
8
72,110,565
2022-5-4
https://stackoverflow.com/questions/72110565/i-want-to-create-python-logo-using-turtle-module
I want to create Python LOGO. So I import Turtle Module into my code. My problem is it creates only half Python LOGO and then throws errors. How can I resolve it? Python Logo Using Python Turtle | Cool Python Turtle Graphics | Python Turtle coding| coding I'm trying to create a PYTHON LOGO using turtle module. However,...
Taking advantage of turtle's methods, we can come up with an approximation of the Python logo with less code: from turtle import Screen, Turtle def curved_box(t, sides): for _ in range(sides): t.circle(90, extent=90) t.forward(120) t.circle(90, extent=90) def snake(t, color): t.backward(16) t.left(90) t.forward(16) t.r...
4
3
72,118,600
2022-5-4
https://stackoverflow.com/questions/72118600/subtract-first-and-last-element-wrap-around-in-numpy-diff
I have a large 100000,6 array and would like to find the diffence to the each element in the vector. np.diff is almost exactly what I need but also want it to wrap around and it also finds the differnce in the first and last element. Toy model: array=np.array([[0,2,4],[0,3,6]]) np.diff(array,axis=1) gives [[2,2],[3,3]...
You can use numpy.roll: np.roll(array, -1, axis=1)-array Output: array([[ 2, 2, -4], [ 3, 3, -6]])
4
3
72,118,249
2022-5-4
https://stackoverflow.com/questions/72118249/why-are-the-branchless-and-built-in-functions-slower-in-python
I found 2 branchless functions that find the maximum of two numbers in python, and compared them to an if statement and the built-in max function. I thought the branchless or the built-in functions would be the fastest, but the fastest was the if-statement function by a large margin. Does anybody know why this is? Here...
Your expectations about branching vs. branchless code apply to low-level languages like assembly and C. Branchless code can be faster in low-level languages because it prevents slowdowns caused by branch prediction misses. (Note: this means branchless code can be faster, but it will not necessarily be.) Python is a hig...
11
15
72,115,626
2022-5-4
https://stackoverflow.com/questions/72115626/why-does-the-stripe-signature-header-never-match-the-signature-of-request-body
I'm using Python with the Django Rest framework and am trying to receive webhook events correctly from stripe. However I constantly get this error: stripe.error.SignatureVerificationError: No signatures found matching the expected signature for payload This is the code: WEBHOOK_SECRET = settings.STRIPE_WEBHOOK_SK @cs...
When Stripe calculates the signature for the Event it sends you, it uses a specific "payload" representing the entire Event's content. The signature is done on that exact payload and any change to it such as adding a new line, removing a space or changing the order of the properties will change the payload and the corr...
4
7
72,113,469
2022-5-4
https://stackoverflow.com/questions/72113469/why-are-python-project-files-copied-after-installing-requirements-in-dockerfile
Take the sample from https://docs.docker.com/language/python/build-images/ for instance: # ... COPY requirements.txt requirements.txt RUN pip3 install -r requirements.txt COPY . . # ... vs # ... COPY . . RUN pip3 install -r requirements.txt # ... What are the disadvantages of the latter?
Docker checks every ADD and COPY statement to see if any files have changed and invalidate the cache for it and every later step if it has. So, in the later, after changes in your code, all requirements will be reinstalled.
4
1
72,112,131
2022-5-4
https://stackoverflow.com/questions/72112131/change-figure-size-in-matplotlib
This is my code and I want to make the plot bigger so it's easier to read. Here I'm trying to get feature importance based on mean decrease in impurity. I'm getting some output but since my barplot has 63 bins, I want it much bigger. I tried everything that is commented. Can someone please suggest how can I make this b...
Use fig.set_size_inches before plt.show(): width = 8 height = 6 fig.set_size_inches(width, height)
4
7
72,107,669
2022-5-4
https://stackoverflow.com/questions/72107669/how-to-get-all-possible-parentheses-combinations-for-an-expression-with-python
Given a list of several elements, find all the possible parentheses combinations. For example with [1, 2, 3, 4], it would return [ [1,2,3,4], [[1,2],3,4], [[1,2],[3,4]], [1,[2,3],4], [1,2,[3,4]], [[1,2,3],4], [[[1,2],3],4], [[1,[2,3]],4], [1,[2,3,4]], [1,[[2,3],4]], [1,[2,[3,4]]] ] in no paticular order. PLEASE READ: ...
To list all the possible trees from the list: Iterate on all the possible number of children from the root; For a chosen number of children, iterate on all the possible ways to split the list into that number of sublists; Recursively find all the possible subtrees of the sublists; Combine all the possible subtrees of ...
5
1
72,111,280
2022-5-4
https://stackoverflow.com/questions/72111280/valueerror-tokenizer-class-mariantokenizer-does-not-exist-or-is-not-currently-i
Get this error when trying to run a MarianMT-based nmt model. Traceback (most recent call last): File "/home/om/Desktop/Project/nmt-marionmt-api/inference.py", line 45, in <module> print(batch_inference(model_path="en-ar-model/Mark2", text=text)) File "/home/om/Desktop/Project/nmt-marionmt-api/inference.py", line 15, i...
Installing SentencePiece worked for me. pip install sentencepiece
4
1
72,052,908
2022-4-29
https://stackoverflow.com/questions/72052908/how-to-return-and-download-excel-file-using-fastapi
How do I return an excel file (version: Office365) using FastAPI? The documentation seems pretty straightforward. But, I don't know what media_type to use. Here's my code: import os from fastapi import FastAPI from fastapi.responses import FileResponse from pydantic import BaseModel from typing import Optional excel_fi...
You could set the Content-Disposition header using the attachment parameter, indicating to the web browser that the file should be downloaded, as described in the answers here and here. Swagger UI will provide a Download file link for you to download the file, as soon as you execute the request. headers = {'Content-Dis...
6
11
72,064,986
2022-4-30
https://stackoverflow.com/questions/72064986/mathematical-explanation-of-leetcode-question-container-with-most-water
I was working on a medium level leetcode question 11. Container With Most Water. Besides the brute force solution with O(n^2), there is an optimal solution with complexity of O(n) by using two pointers from left and right side of the container. I am a little bit confused why this "two pointers" method must include the ...
Based on my understanding the idea is roughly: Starting from the farthest-apart bars (i.e. first and last bar) and then narrowing width to find potentially better pair(s). Steps: We need to have the ability to loop over all 'potential' candidates (the candidates better than what we have on hand rather than all candi...
5
2
72,103,359
2022-5-3
https://stackoverflow.com/questions/72103359/format-a-jupyter-notebook-on-save-in-vscode
I use black to automatically format all of my Python code whenever I save in VSCode. I'd like the same functionality, but within a Jupyter notebook in VSCode. This answer shows how to right click and format a cell or a whole notebook from the right click context menu, or a keyboard shortcut. Can I make this happen on s...
Good news! This is now an option in the newest VSCode release (1.77) Setting "notebook.formatOnSave.enabled": true will do the trick. You can read more about it here. If you have black already enabled for Python it should work fine.
15
20
72,093,397
2022-5-2
https://stackoverflow.com/questions/72093397/how-do-you-input-and-output-text-with-pyscript
I’m learning py-script where you can use <py-script></py-script> in an HTML5 file to write Python Code. As a python coder, I would like to try web development while still using python, so it would be helpful if we could output and input information using py-script. For example, could someone explain how to get this fun...
I checked source code on GitHub and found folder examples. Using files todo.html and todo.py I created this index.html (which I tested using local server python -m http.server) Some elements I figured out because I have some experience with JavaScript and CSS - so it could be good to learn JavaScript and CSS to work wi...
6
10
72,068,789
2022-4-30
https://stackoverflow.com/questions/72068789/keeping-both-dataframe-indexes-on-merge
I'm sure this question must have already been answered somewhere but I couldn't find an answer that suits my case. I have 2 pandas DataFrames a = pd.DataFrame({'A1':[1,2,3], 'A2':[2,4,6]}, index=['a','b','c']) b = pd.DataFrame({'A1':[3,5,6], 'A2':[3,6,9]}, index=['a','c','d']) I want to merge them in order to obtain s...
You could use pd.concat to create one dataframe (b being the first one as it is b that has a priority for it's values to be kept over a), and then drop the duplicated index: Using your sample data: c = pd.concat([b,a]) c[~c.index.duplicated()].sort_index() prints: A1 A2 a 3 3 b 2 4 c 5 6 d 6 9
4
3
72,036,397
2022-4-27
https://stackoverflow.com/questions/72036397/boto3-keyconditionexpression-on-both-partition-and-sort-key
So i have the following schema: domain (partition key) time_stamp (sort key) I am (attempting) to use boto to query dynamo. I want to return all records with a given domain, after a given time_stamp. I have tried a couple of different approaches to no avail: First is my ideal approach. I believe it to be much cleaner i...
You have to use & not and. resp = table.query( KeyConditionExpression=Key('domain').eq(domain) & Key('time_stamp').between(start,end), ProjectionExpression= 'time_stamp,event_type,country,tablet,mobile,desktop') This is where the AWS docs say this, but it's kind of buried in there.
4
4
72,083,071
2022-5-2
https://stackoverflow.com/questions/72083071/mypy-doesnt-recognize-sqlalchemy-columns-with-hybrid-property
I'm trying to use mypy with SQLAlchemy. In order to validate/modify specific column value (email in this case), SQLAlchemy official document provides hybrid_property decorator. The problem is, mypy doesn't recognize EmailAddress class constructor properly, it gives: email_address.py:31: error: Unexpected keyword argume...
OK, it seems like I finally found a way to solve the problem. This reminds me of uncooperative behaviors between dataclass/property decorators discussed in here. I end up with splitting EmailAddress class into 2: Use @dataclass decorator on base class in order to indicate constructor options. Override email property s...
6
0
72,029,857
2022-4-27
https://stackoverflow.com/questions/72029857/no-module-named-tensorflow-compat
I'm trying to use the code from the Teachable Machine website: from keras.models import load_model from PIL import Image, ImageOps import numpy as np # Load the model model = load_model('keras_model.h5') # Create the array of the right shape to feed into the keras model # The 'length' or number of images you can put in...
This just happened to me but I figured it out. Your .py script filename is the same with one of the files of the tensorflow library. You can just rename your python script and it will work fine.
10
7
72,102,435
2022-5-3
https://stackoverflow.com/questions/72102435/how-to-install-python-3-6-on-ubuntu-22-04
I need to install this specific Python version, to prepare a developer environment, because I'm maintaining a system with multiple libraries based on python 3.6.9. I recently installed Ubuntu 22.04 on my laptop, but I had no success trying to install this python version. I tried to install with apt-get after adding the...
I have faced the same problems and could make it work by adding some additional flags when running ./configure Here are my steps: Step 1 – Prerequsities sudo apt-get install -y make build-essential libssl-dev zlib1g-dev \ libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev \ libncursesw5-dev xz-uti...
41
96
72,087,819
2022-5-2
https://stackoverflow.com/questions/72087819/pydantic-set-attribute-field-to-model-dynamically
According to the docs: allow_mutation whether or not models are faux-immutable, i.e. whether setattr is allowed (default: True) Well I have a class : class MyModel(BaseModel): field1:int class Config: allow_mutation = True If I try to add a field dynamically : model1 = MyModel(field1=1) model1.field2 = 2 And I get ...
You can use the Config object within the class and set the extra attribute to "allow" or use it as extra=Extra.allow kwargs when declaring the model Example from the docs : from pydantic import BaseModel, ValidationError, Extra class Model(BaseModel, extra=Extra.forbid): a: str try: Model(a='spam', b='oh no') except Va...
12
9
72,032,032
2022-4-27
https://stackoverflow.com/questions/72032032/importerror-cannot-import-name-iterable-from-collections-in-python
Working in Python with Atom on a Mac. Code: from rubik.cube import Cube from rubik_solver import utils Full error: Traceback (most recent call last): File "/Users/Audey/Desktop/solver.py", line 2, in <module> from rubik_solver import utils File "/Users/Audey/Library/Python/3.10/lib/python/site-packages/rubik_solver/ut...
The Iterable abstract class was removed from collections in Python 3.10. See the deprecation note in the 3.9 collections docs. In the section Removed of the 3.10 docs, the item Remove deprecated aliases to Collections Abstract Base Classes from the collections module. (Contributed by Victor Stinner in bpo-37324.) is ...
50
88
72,097,725
2022-5-3
https://stackoverflow.com/questions/72097725/converting-py-files-to-ipynb
My organisation converts any Jupyter Notebooks (.ipynb files) it makes into python scripts (.py files) for easier management in our repos. I need to convert them back so I can run the notebooks but can't work out how. I believe they've been encoded using the nbconvert package but I couldn't find a way to convert the fi...
Looks like the file was actually converted using program jupytext. To convert it back I found running jupytext --to ipynb my_file.py worked. More simply: opening the .py file in jupyter notebook allowed me to view the .py file as if it were a .ipynb file without converting.
4
4
72,097,417
2022-5-3
https://stackoverflow.com/questions/72097417/segfault-using-htop-on-aws-sagemaker-pytorch-1-10-cpu-py38-app
I am trying to launch the htop command in the Pytorch 1.10 - Python 3.8 CPU optimized AWS Sagemaker container. This works fine in other images I have used till now, but in this one, the command fails with a segfault: htop htop: /opt/conda/lib/libncursesw.so.6: no version information available (required by htop) htop: /...
I fixed this with # Note: add sudo if needed: ln -fs /lib/x86_64-linux-gnu/libncursesw.so.6 /opt/conda/lib/libncursesw.so.6
4
3
72,073,919
2022-5-1
https://stackoverflow.com/questions/72073919/graph-tool-stochastic-block-model-vs-leiden
I'm calculating network communities for 4 networks using 2 methods: 'Leiden' method, which gives me 7 (a), 13 (b), 19 (c), 22 (d) communities. 'Stochastic block Model', also checking group membership of the nodes by inspecting levels of the hierarchy, like so: state = gt.inference.minimize_nested_blockmodel_dl(g)...
The method of modularity maximization (of which Leiden is an implementation) has two important properties: It only searches for assortative communities (i.e. groups with more internal connections than external ones). It is a statistically inconsistent method, that will both overfit and underfit, depending on the situa...
4
3
72,044,314
2022-4-28
https://stackoverflow.com/questions/72044314/how-to-validate-data-received-via-the-telegrams-web-app
I'm trying to validate WebApp data but the result is not what I wanted. Telegram documentation: data_check_string = ... secret_key = HMAC_SHA256(<bot_token>, "WebAppData") if (hex(HMAC_SHA256(data_check_string, secret_key)) == hash) { // data is from Telegram } MyCode: BOT_TOKEN = '5139539316:AAGVhDje2A3mB9yA_7l8-TV8x...
You need to unquote data_check_string from urllib.parse import unquote data_check_string = unquote('query_id=AAGcqlFKAAAAAJyqUUp6-Y62&user=%7B%22id%22%3A1246866076%2C%22first_name%22%3A%22Dante%22%2C%22last_name%22%3A%22%22%2C%22username%22%3A%22S_User%22%2C%22language_code%22%3A%22en%22%7D&auth_date=1651689536&hash=de...
4
1
72,101,578
2022-5-3
https://stackoverflow.com/questions/72101578/using-string-parameter-for-nvidia-triton
I'm trying to deploy a simple model on the Triton Inference Server. It is loaded well but I'm having trouble formatting the input to do a proper inference request. My model has a config.pbtxt set up like this max_batch_size: 1 input: [ { name: "examples" data_type: TYPE_STRING format: FORMAT_NONE dims: [ -1 ] is_shape...
If anyone gets this same problem, this solved it. I had to create a tf.train.Example() and set the data correctly example = tf.train.Example() example_bytes = str.encode(input_data) example.features.feature['utterance'].bytes_list.value.extend([example_bytes]) inputs = [ httpclient.InferInput('examples', [1], "BYTES"),...
4
2
72,074,882
2022-5-1
https://stackoverflow.com/questions/72074882/call-r-object-from-python-with-r-in-a-quarto-document
I try to call an R object from Python inside a Quarto document: --- title: "pandas" format: html jupyter: python3 --- ```{r} data("penguins", package = "palmerpenguins") ``` ```{python} penguins=r.penguins penguins ``` When I execute the chunks one by one in RStudio, everything is okay: > data("penguins", package = "p...
Quarto have two engines for render, knitr and jupyter.A related document is here. If we use: --- title: "pandas" format: html --- ```{r} data("penguins", package = "palmerpenguins") ``` ```{python} penguins=r.penguins penguins ``` The engine will be knitr. And while render, knitr will use reticulate(R Interface to Pyt...
4
7
72,049,386
2022-4-28
https://stackoverflow.com/questions/72049386/sqlalchemy-multi-column-constraint
I have a number of tables in different schemas, I used the pattern from the docs. Some of my tables require multi column constraints and it was unclear what the dictionary key would be for declaring that unique constraint as they mention in the section above In my model below, I'd like to create a unique constraint wit...
I think I encountered that issue a while back. If I remember correctly, it was just a matter of moving the "schema dict" to inside a tuple which also contains your constraints. I can try to dig further if that does not work, but the documentation seems to agree that using declarative table configuration via __table_arg...
4
4
72,106,357
2022-5-3
https://stackoverflow.com/questions/72106357/access-objects-in-pyspark-user-defined-function-from-outer-scope-avoid-pickling
How do I avoid initializing a class within a pyspark user-defined function? Here is an example. Creating a spark session and DataFrame representing four latitudes and longitudes. import pandas as pd from pyspark import SparkConf from pyspark.sql import SparkSession conf = SparkConf() conf.set('spark.sql.execution.arrow...
You will need a cached instance of the object on every worker. You could do that as follows instance = [None] def func(iterator: Iterator[pd.DataFrame]) -> Iterator[pd.DataFrame]: if instance[0] is None: instance[0] = TimezoneFinder() tzf = instance[0] for dx in iterator: dx['timezone'] = [tzf.timezone_at(lng=a, lat=b)...
7
5
72,083,187
2022-5-2
https://stackoverflow.com/questions/72083187/in-django-what-are-media-root-and-media-url-exactly
I read the documentation about MEDIA_ROOT and MEDIA_URL then I could understand them a little bit but not much. MEDIA_ROOT: Absolute filesystem path to the directory that will hold user-uploaded files. MEDIA_URL: URL that handles the media served from MEDIA_ROOT, used for managing stored files. It must end in a slas...
First of all, I explain about "MEDIA_ROOT" then "MEDIA_URL". <MEDIA_ROOT> "MEDIA_ROOT" sets the absolute path to the directory where uploaded files are stored and setting "MEDIA_ROOT" never ever influence to media file URL. For example, we have a django project: Then, we set "os.path.join(BASE_DIR, 'media')" which is ...
4
13
72,082,251
2022-5-2
https://stackoverflow.com/questions/72082251/error-in-layer-of-discriminator-model-while-making-a-gan-model
I made a GAN model for generating the images based on sample training images of animes. Where on the execution of the code I got this error. ValueError: Input 0 of layer "discriminator" is incompatible with the layer: expected shape=(None, 64, 64, 3), found shape=(64, 64, 3) Even changing the shape of the 1st layer of...
The problem is you are extracting exactly one batch when running xtrain, ytrain = next(iter(train_ds)) and you are then iterating over this batch in your training loop. That is why you are missing the batch dimension (None). I am not sure what your dataset looks like, but here is a working example using tf.keras.utils....
4
5
72,063,166
2022-4-29
https://stackoverflow.com/questions/72063166/read-and-group-json-files-by-date-element-using-pyspark
I have multiple JSON files (10 TB ~) on a S3 bucket, and I need to organize these files by a date element present in every json document. What I think that my code needs to do Read all json files in the s3 bucket. Keep all documents which have the element "creation_date" between 2022-01-01 and 2022-04-01 Save them in ...
Do you want to run the job only once or do you want to do it periodically? One run What you have should work well # Trying to read all the json files sdf = spark.read.json("s3://my-bucket/**/**/*.json") The only thing I'd add is to partition the output by the date to speed up queries: ( # Filtering all documents that ...
5
6
72,103,585
2022-5-3
https://stackoverflow.com/questions/72103585/how-to-pass-file-object-to-httpx-request-in-fastapi-endpoint
The idea is to get file object from one endpoint and send it to other endpoints to work with it without saving it. Let's have this expample code: import httpx from fastapi import Request, UploadFile, File app = FastAPI() client = httpx.AsyncClient() @app.post("/endpoint/") async def foo(request: Request, file: UploadFi...
httpx similar to requests uses files=.... to send files. ie. post(..., files={'file': file.file}, ...) or with filename post(..., files={'file': (file.filename, file.file)}, ...) BTW: If you send the same file a few times then you may need to move pointer to the beginning of file after sending file.file.seek(0) or ...
6
8
72,041,522
2022-4-28
https://stackoverflow.com/questions/72041522/how-to-add-title-to-the-plot-of-shap-plots-force-with-matplotlib
I want to add some modifications to my force plot (created by shap.plots.force) using Matplotlib, e.g. adding title, using tight layout etc. However, I tried to add title and the title doesn't show up. Any ideas why and how can I add the title using Matplotlib? import numpy as np import shap import matplotlib.pyplot as...
The last lines in force_plot are: if show: plt.show() else: return plt.gcf() so, if you set show = False you can get prepared SHAP plot as figure object and customize it to your needs as usual: import shap myBaseline = 1.5 shap_values_0 = np.array([-1, -4, 3]) test_point_0 = np.array([11, 12, 13]) features_names = ["a...
4
6
72,101,566
2022-5-3
https://stackoverflow.com/questions/72101566/should-i-use-a-capital-l-list-for-type-hinting-in-python-3-9
In Python 3.9+ I can write list_of_integers: list[int], but I see senior developers using the older syntax (even in Python 3.9 and 3.10 scripts): from typing import List list_of_integers: List[int] Is this superior for backwards compatibility and explicitness?
When the current version of documentation for typing.List says: Deprecated since version 3.9: builtins.list now supports []. See PEP 585 and Generic Alias Type. It should be considered best practice unless you have a compelling reason not to use it (like what you said about backward compatibility for older versions o...
16
9
72,061,965
2022-4-29
https://stackoverflow.com/questions/72061965/create-voronoi-art-with-rounded-region-edges
I'm trying to create some artistic "plots" like the ones below: The color of the regions do not really matter, what I'm trying to achieve is the variable "thickness" of the edges along the Voronoi regions (espescially, how they look like a bigger rounded blob where they meet in corners, and thinner at their middle poi...
This is what @JohanC suggestion looks like. IMO, it looks much better than my attempt with Bezier curves. However, there appears to be a small problem with the RoundedPolygon class, as there are sometimes small defects at the corners (e.g. between blue and purple in the image below). Edit: I fixed the RoundedPolygon cl...
6
5
72,096,495
2022-5-3
https://stackoverflow.com/questions/72096495/how-to-rename-a-column-for-a-dataframe-in-pyspark
below is part code: df = None F_DATE = ['202101', '202102', '202103'] for date in F_DATE: if df is None: df = spark.sql("select count(*) as Total_count from test_" + date) else: df2 = spark.sql("select count(*) as Total_count from test_" + date) df = df.union(df2) df.write.csv('/csvs/test.csv') I tried 'toDF()', 'with...
You can use: df = df.withColumnRenamed('old_name', 'new_name')
4
4
72,091,572
2022-5-2
https://stackoverflow.com/questions/72091572/how-to-compute-cross-entropy-loss-for-sequences
I have a sequence continuation/prediction task (input: a sequence of class indices, output: a sequence of class indices) and I use Pytorch. My neural network returns a tensor of shape (batch_size, sequence_length, numb_classes) where the entries are a number proportional to the propability that the class with this inde...
The documentation page of nn.CrossEntropyLoss clearly states: Input: shape (C), (N, C) or (N, C, d_1, d_2, ..., d_K) with K >= 1 in the case of K-dimensional loss. Target: If containing class indices, shape (), (N) or (N, d_1, d_2, ..., d_K) with K >= 1 in the case of K-dimensional loss where each value should be betw...
5
2
72,083,896
2022-5-2
https://stackoverflow.com/questions/72083896/how-to-stretch-a-line-to-fit-image-with-python-opencv
I have an image with the size of W * H, I want to draw a line on this and the line should be automatically fit to the image, for example if I draw it: I want this: How can I do this in Python and OpenCV? Thanks
Method #1: Just drawing the extended line (no coordinates) Before -> After Here's a function when given points p1 and p2, will only draw the extended line. By default, the line is clipped by the image boundaries. There is also a distance parameter to determine how far to draw from the original starting point or until...
6
7
72,092,993
2022-5-2
https://stackoverflow.com/questions/72092993/i-want-to-use-boto3-in-async-function-python
I am developing web-scraper in playwright and want to upload images to aws-s3 asynchronouslly. but boto3 is not an async function.. how to fix it? class Boto3: def __init__(self, key, id): self.S3 = boto3.client('s3', aws_access_key_id=aws_key_id, aws_secret_access_key=aws_secret) def upload_stream(self, stream, bucke...
How to fix it? You can't, as boto3 is not async. At best you can try a third party, non-AWS library, such as aioboto3 in place of boto3.
16
20
72,090,856
2022-5-2
https://stackoverflow.com/questions/72090856/where-is-the-interp-function-in-numpy-core-multiarray-located
The source code for numpy.interp calls a compiled_interp function which is apparently the interp function imported from numpy.core.multiarray. I went looking for this function but I can not find it inside that file. What am I missing?
The interp Python function of numpy.core.multiarray is exported in multiarraymodule.c. It is mapped to arr_interp which is a C function defined in compiled_base.c. The heart of the computation can be found here.
4
4
72,076,793
2022-5-1
https://stackoverflow.com/questions/72076793/membership-for-list-of-arrays-valueerror-the-truth-value-of-an-array-with-more
Q = [np.array([0, 1]), np.array([1, 2]), np.array([2, 3]), np.array([3, 4])] for q in Q: print(q in Q) Running the code above, it gives me the result 'True' at the first iteration, while ValueError comes out afterwards. True ValueError: The truth value of an array with more than one element is ambiguous. Use a.any(...
Essentially, you can't use in to test for numpy arrays in a Python list. It will only ever work for the first element, because of an optimisation in the way Python tests for equality. What's happening is that the implementation for list.__contains__ (which in defers to), is using a short-cut to find a match faster, by ...
4
5
72,072,824
2022-4-30
https://stackoverflow.com/questions/72072824/python-how-to-get-enum-value-by-index
I have an Enum of days_of_the week in Python: class days_of_the_week(str, Enum): monday = 'monday' tuesday = 'tuesday' wednesday = 'wednesday' thursday = 'thursday' friday = 'friday' saturday = 'saturday' sunday = 'sunday' I want to access the value using the index. I've tried: days_of_the_week.value[index] days_of_t...
IIUC, you want to do: from enum import Enum class days_of_the_week(Enum): monday = 0 tuesday = 1 wednesday = 2 thursday = 3 friday = 4 saturday = 5 sunday = 6 >>> days_of_the_week(1).name 'tuesday'
11
11
72,071,447
2022-4-30
https://stackoverflow.com/questions/72071447/python-enum-and-pydantic-accept-enum-members-composition
I have an enum : from enum import Enum class MyEnum(Enum): val1 = "val1" val2 = "val2" val3 = "val3" I would like to validate a pydantic field based on that enum. from pydantic import BaseModel class MyModel(BaseModel): my_enum_field: MyEnum BUT I would like this validation to also accept string that are composed by ...
I looked at this a bit further, and I believe something like this could be helpful. You can create a new class to define the property that is a list of enum values. This class can supply a customized validate method and supply a __modify_schema__ to keep the information present about being a string in the json schema. ...
9
7
72,062,001
2022-4-29
https://stackoverflow.com/questions/72062001/remove-everything-of-a-specific-color-with-a-color-variation-tolerance-from-an
I have some text in blue #00a2e8, and some text in black on a PNG image (white background). How to remove everything in blue (including text in blue) on an image with Python PIL or OpenCV, with a certain tolerance for the variations of color? Indeed, every pixel of the text is not perfectly of the same color, there are...
Your image has some issues. Firstly, it has a completely superfluous alpha channel which can be ignored. Secondly, the colours around your blues are quite a long way from blue! I used your planned approach and found the removal was pretty poor: #!/usr/bin/env python3 import cv2 import numpy as np # Load image im = cv2....
4
10
72,059,811
2022-4-29
https://stackoverflow.com/questions/72059811/how-to-create-a-new-dataframe-column-with-a-set-of-nested-if-rules-apply-is-ver
What I need I need to create new columns in pandas dataframes, based on a set of nested if statements. E.g. if city == 'London' and income > 10000: return 'group 1' elif city == 'Manchester' or city == 'Leeds': return 'group 2' elif borrower_age > 50: return 'group 3' else: return 'group 4' This is actually a simplifc...
Try with numpy.select: conditions = [df["city"].eq("London") & df["income"].gt(10000), df["city"].isin(["Manchester", "Leeds"]), df["borrower_age"].gt(50)] choices = ["Group 1", "Group 2", "Group 3"] df["New Field"] = np.select(conditions, choices, "Group 4") Or have the conditions as a dictionary and use that in the ...
4
4
72,062,542
2022-4-29
https://stackoverflow.com/questions/72062542/is-there-a-way-to-filter-out-items-from-relatedmanager-in-a-modelviewset
I'm using DRF for a simple API, and I was wondering if there's a way to achieve this behavior: I've got two models similar to the following: class Table(models.Model): name = models.CharField(max_length=100) ... class Column(models.Model): original_name = models.CharField(max_length=100) name = models.CharField(max_l...
You can work with a Prefetch object [Django-doc] to filter the related object collection, so: from django.db.models import Prefetch class TableViewSet(viewsets.ModelViewSet): serializer_class = TableSerializer def get_queryset(self): queryset = Table.objects.prefetch_related( Prefetch('columns', Column.objects.filter(n...
4
5
72,059,380
2022-4-29
https://stackoverflow.com/questions/72059380/python-fuctional-style-iterative-algoritm
In Haskell there is a simple list function available iterate :: (a -> a) -> a -> [a] iterate f x = x : iterate f (f x) In python it could be implemented as following: def iterate(f, init): while True: yield init init = f(init) I was kinda surprised that something basic like this is not part of the functools/itertools...
You can do it using some of the functions in itertools: from itertools import accumulate, repeat def iterate(func, initial): return accumulate(repeat(None), func=lambda tot, _: func(tot), initial=initial) Although it's clearly not very clean. Itertools is missing some fundamental functions for constructing streams, li...
11
9
72,051,076
2022-4-28
https://stackoverflow.com/questions/72051076/rotating-qr-code-to-the-correct-position-using-python-opencv
I'm a beginner in python and currently studying QR code detection and decoding. I'm having a hard time rotating the detected QR code to the right position. I already used minAreaRect() to rotate my QR code but it doesn't work. Is there any workaround or a right way to do this? thanks! ROI2 = cv2.imread('ROI.png') gray2...
From my understanding, you're trying to deskew an image. To do this, we need to first compute the rotated bounding box angle then perform a linear transformation. The idea is to use cv2.minAreaRect + cv2.warpAffine. According to the documentation, cv2.minAreaRect returns (center(x, y), (width, height), angle of rotatio...
5
6
72,050,038
2022-4-28
https://stackoverflow.com/questions/72050038/use-numpy-to-apply-a-fixed-palette-to-an-image
I have a NumPy image in RGB bytes, let's say it's this 2x3 image: img = np.array([[[ 0, 255, 0], [255, 255, 255]], [[255, 0, 255], [ 0, 255, 255]], [[255, 0, 255], [ 0, 0, 0]]]) I also have a palette that covers every color used in the image. Let's say it's this palette: palette = np.array([[255, 0, 255], [ 0, 255, 0]...
Edit Here is a faster way that uses np.searchsorted. def rev_lookup_by_sort(img, palette): M = (1 + palette.max())**np.arange(3) p1d, ix = np.unique(palette @ M, return_index=True) return ix[np.searchsorted(p1d, img @ M)] Correctness (by equivalence to rev_lookup_by_dict() in the original answer below): np.array_equal...
4
3
72,050,177
2022-4-28
https://stackoverflow.com/questions/72050177/futurewarning-dropping-of-nuisance-columns-in-dataframe-reductions-warning-wh
I have a dataframe that looks something like this: col1 col2 col3 0 1 True abc 1 2 False def 2 3 True ghi When I run df.mean(), it shows a warning: >>> df.mean() <stdin>:1: FutureWarning: Dropping of nuisance columns in DataFrame reductions (with 'numeric_only=None') is deprecated; in a future version this will raise...
Numeric functions such as mean, median, sem, skew, etc., only support dealing with numeric values. If you look at the data types of your columns... >>> df.dtypes col1 int64 col2 bool col3 object dtype: object ...you can see that the dtype of col1 is int64, which mean can handle, because it's numeric. Likewise, the dty...
6
7
72,044,305
2022-4-28
https://stackoverflow.com/questions/72044305/regex-on-bytes-in-python
I would like to extract 10.00ML in following byte: b'\x0200S10.00ML\x03' So I've tried extracting the 10.00ML between 200S and \x03: result = re.search(b'200S(.*)x03', b'\x0200S10.00ML\x03') which didn't work, no element was found: AttributeError: 'NoneType' object has no attribute 'group' Using only strings I have a...
You can use import re text = b'\x0200S10.00ML\x03' m = re.search(rb'\x0200S(.*?)\x03', text, re.S) if m: print( m.group(1).decode('utf-8') ) # => 10.00ML Note that \x02 and \x03 are START OF HEADING and START OF TEXT control chars, so you cannot match them as literal text.
4
5
72,039,810
2022-4-28
https://stackoverflow.com/questions/72039810/python-3-10-optional-parameter-type-union-vs-none-default
It's not a huge issue, but as a matter of style, I was wondering about the best way to indicate optional function parameters... Before type hints, it was like this for parameter b: def my_func(a, b = None) Before Python 3.10, using type hints: def my_func(a, b: Optional[str]) With Python 3.10's lovely pipe-type notat...
Per PEP-484: A past version of this PEP allowed type checkers to assume an optional type when the default value is None, as in this code: def handle_employee(e: Employee = None): ... This is no longer the recommended behavior. Type checkers should move towards requiring the optional type to be made explicit. So the o...
7
12
72,038,297
2022-4-28
https://stackoverflow.com/questions/72038297/find-positive-and-negative-bin-limits-based-on-multiple-other-columns
I have a dataframe like as shown below ID raw_val var_name constant s_value 1 388 Qty 0.36 -0.032 2 120 Qty 0.36 -0.007 3 34 Qty 0.36 0.16 4 45 Qty 0.36 0.31 1 110 F1 0.36 -0.232 2 1000 F1 0.36 -0.17 3 318 F1 0.36 0.26 4 419 F1 0.36 0.31 My objective is to a) Find the upper and lower limits (of raw_val) for each valu...
I think numpy.where with aggregate minimal and maximal values is way: df['sign'] = np.where(df['s_value']<0, 'neg', 'pos') df1 = (df.groupby(['var_name','sign'], sort=False, as_index=False) .agg(low_limit=('raw_val','min'), upp_limit=('raw_val','max'))) print (df1) var_name sign low_limit upp_limit 0 Qty neg 120 388 1 ...
4
4
72,034,176
2022-4-27
https://stackoverflow.com/questions/72034176/adjust-the-size-of-the-text-label-in-plotly
I'm trying to adjust the text size according to country size, so the text will be inside the boarders of the country. Here's my code: # imports import pandas as pd import plotly.express as px # uploading file df=pd.read_csv('regional-be-daily-latest.csv', header = 1) # creating figure fig = px.choropleth(df, locations=...
You can set the font size using the update_layout function and specifying the font's size by passing the dictionary in the font parameter. import pandas as pd import plotly.express as px df=pd.read_csv('regional-be-daily-latest.csv', header = 1) fig = px.choropleth(df, locations='Code', color='Track Name') fig.update_l...
16
21
72,033,491
2022-4-27
https://stackoverflow.com/questions/72033491/how-to-make-python-module-yt-dlp-ignore-private-videos-when-downloading-a-playli
I'm Downloading a Playlist which has some hidden Videos so python gives me DownloadError, I want to Download the Whole Playlist at once. Is there a fix for that. I'm trying to see if I can make it ignore those hidden videos My Code: from yt_dlp import YoutubeDL url = 'https://www.youtube.com/playlist?list=PLzMXToX8Kzqh...
Based on my understanding of the documentation, I think this will do what you want - unfortunately I cannot test it at the moment, so let me know if it doesn't work: import yt_dlp ydl_opts = { 'ignoreerrors': True } url = 'https://www.youtube.com/playlist?list=PLzMXToX8KzqhKrURIhVTJMb0v-HeDM3gs' with yt_dlp.YoutubeDL(y...
5
3
72,031,814
2022-4-27
https://stackoverflow.com/questions/72031814/set-a-class-attribute-in-pytest-fixture
I'm making a test class for pytest, I want to set a class attribute a that will be used for several test methods. To do so, I used a fixture set_a, which is launched automatically autouse=True, and invoked only once for the class (scope='class'), because setting a is costly. Here is my code: import pytest import time c...
You shouldn’t set the scope since you are already in the class. class Test: @pytest.fixture(autouse=True) def set_a(self): print("Setting a...") time.sleep(5) self.a = 1 def test_1(self): print("TEST 1") assert self.a == 1 This is how you should use the scope=class, meaning it will work for any class in your module: @...
6
1
72,025,924
2022-4-27
https://stackoverflow.com/questions/72025924/key-shortcut-for-running-python-file-in-vs-code
In VS Code, I'm writing python code. I was wondering if there is a key shortcut to run the file instead of pressing the run button in the right top corner of the screen constantly.
You can press Ctrl + F5 to run the file. If you want to debug the file, use F5 instead.
5
3
72,025,278
2022-4-27
https://stackoverflow.com/questions/72025278/how-to-slice-a-nested-list-twice
With a nested list like: ex_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] I need to be able to slice this list for: [[1, 2], [4, 5]] I've been trying: list(ex_list[:2][:2]) but this isn't working. I'm obviously doing something very wrong but haven't been able to find a solution as using commas doesn't work either for som...
You should try using comprehension: Try: [i[:2] for i in ex_list[:2]] Code: ex_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print([i[:2] for i in ex_list[:2]]) Output: [[1, 2], [4, 5]]
4
4
72,022,176
2022-4-27
https://stackoverflow.com/questions/72022176/warning-cant-open-read-file-check-file-path-integrity
images_per_class = 80 fixed_size = tuple((500, 500)) train_path = "dataset/train" train_labels = os.listdir(train_path) for training_name in train_labels: dir = os.path.join(train_path, training_name) current_label = training_name for x in range(1,images_per_class+1): # get the image file name file = dir + "/" + str(x)...
file = dir + "/" + str(x) + ".jpg" try to replace this line with : file = dir + "\" + str(x) + ".jpg" the / not correct the correct is \
10
0
71,968,447
2022-4-22
https://stackoverflow.com/questions/71968447/python-typing-copy-kwargs-from-one-function-to-another
It is common pattern in Python extend or wrap functions and use **kwargs to pass all keyword arguments to the extended function. i.e. take class A: def bar(self, *, a: int, b: str, c: float) -> str: return f"{a}_{b}_{c}" class B(A): def bar(self, **kwargs): return f"NEW_{super().bar(**kwargs)}" def base_function(*, a: ...
Solution Update: There is currently a CPython PR open to include the following solution into the standard library. PEP 612 introduced the ParamSpec (see Documentation) Type. We can exploit this to generate a decorator that tells our type checker, that the decorated functions has the same arguments as the given function...
11
19
71,961,686
2022-4-21
https://stackoverflow.com/questions/71961686/avoiding-circular-imports-with-type-annotations-in-situations-where-future-a
When I have the following minimum reproducing code: start.py from __future__ import annotations import a a.py from __future__ import annotations from typing import Text import b Foo = Text b.py from __future__ import annotations import a FooType = a.Foo I get the following error: soot@soot:~/code/soot/experimental/a...
In most cases using typing.TYPE_CHECKING should be enough to resolve circular import issues related to use in annotations. Note annotations future-import (details), alternatively you can enclose all names not available at runtime (imported under if TYPE_CHECKING) in quotes. # a.py from __future__ import annotations fro...
5
10
72,005,302
2022-4-25
https://stackoverflow.com/questions/72005302/completely-uninstall-python-3-on-mac
I installed Python 3 on Mac and installed some packages as well. But then I see AWS lamda does not support Python 3 so I decided to downgrade. I removed Python3 folder in Applications and cleared the trash. But still I see a folder named 3 in /Library/Frameworks/Python.framework/Versions which is causing problems, such...
Removing the app does not completely uninstall that version of Python. You will need to remove the framework directories and their symbolic links. Deleting the frameworks sudo rm -rf /Library/Frameworks/Python.framework/Versions/[version number] replacing [version number] with 3.10 in your case. Removing symbolic link...
46
63
71,965,662
2022-4-22
https://stackoverflow.com/questions/71965662/python-black-style-discrepancy
I am using black to format my python code. I observed the following behavior. I admit that it is a very specific case but it goes on my nerves. Let's suppose I have the following code: @pytest.mark.parametrize( "first", ["second"], ) black does not change that. But, if I remove the trailing comma after ["second"]: @py...
The black behavior is expected from my understanding, because one of the purpose is to limit the number of changes inside a git diff. If the line is too long, you already are in a multiline writing. And if you are in a multiline writing, then it should end with a comma. That way if you add elements in the tuple, list, ...
4
8
72,000,572
2022-4-25
https://stackoverflow.com/questions/72000572/how-to-change-python-version-of-azure-function
When I publish my azure cloud functions I get the message: Local python version '3.9.7' is different from the version expected for your deployed Function App. This may result in 'ModuleNotFound' errors in Azure Functions. Please create a Python Function App for version 3.9 or change the virtual environment on your loca...
You can view and set the linuxFxVersion from the Azure CLI. With the az functionapp config set command, you can change the linuxFxVersion setting in the function app. az functionapp config set --name <FUNCTION_APP> \ --resource-group <RESOURCE_GROUP> \ --linux-fx-version "PYTHON|3.9" Please refer Changing Python ver...
8
14
71,959,420
2022-4-21
https://stackoverflow.com/questions/71959420/client-init-missing-1-required-keyword-only-argument-intents-or-tak
I was trying to make a quick bot for discord and I used this code: import discord from discord.ui import button, view from discord.ext import commands client = discord.Client() @client.event async def on_ready(): print('Autenticazione riuscita. {0.user} è online!'.format(client)) But this error pops up: Client.__init_...
You could use the default Intents unless you have a particular one to specify. client = discord.Client(intents=discord.Intents.default()) As the first error message says, it is a keyword-only argument, so you cannot write discord.Client(discord.Intents.default()) without intents=. See Intents for more details.
32
53
71,982,525
2022-4-23
https://stackoverflow.com/questions/71982525/how-to-use-match-case-to-check-for-a-variables-type-in-python
I have this code to check whether or not a variable is a number or a Vector2: def __mul__(self, other): match type(other): case int | float: pass case Vector2: pass If I run this, I get SyntaxError: name capture 'int' makes remaining patterns unreachable And when I hover in vscode, it gives me: "int" is not accessed ...
Case with a variable (ex: case _: or case other:) needs to be the last case in the list. It matches any value, where the value was not matched by a previous case, and captures that value in the variable. A type can be used in a case, but implies isinstance(), testing to determine if the value being matched is an instan...
15
23
71,998,978
2022-4-25
https://stackoverflow.com/questions/71998978/early-stopping-in-pytorch
I tried to implement an early stopping function to avoid my neural network model overfit. I'm pretty sure that the logic is fine, but for some reason, it doesn't work. I want that when the validation loss is greater than the training loss over some epochs, the early stopping function returns True. But it returns False ...
The problem with your implementation is that whenever you call early_stopping() the counter is re-initialized with 0. Here is working solution using an oo-oriented approch with __call__() and __init__() instead: class EarlyStopping: def __init__(self, tolerance=5, min_delta=0): self.tolerance = tolerance self.min_delta...
34
21
71,935,608
2022-4-20
https://stackoverflow.com/questions/71935608/python-enum-auto-generating-warning-that-parameter-is-unfilled
I have the below code that defines an enum and uses enum.auto() to give entries generated values starting from 1: from enum import Enum, auto class Colors(Enum): RED = auto() BLUE = auto() YELLOW = auto() def main(): print(Colors.RED.value) print(Colors.BLUE.value) print(Colors.YELLOW.value) if __name__ == '__main__': ...
Nevermind, everyone. I just found out this was a bug and was reported a month ago here. UPDATE: The bug has finally been fixed! 🎉
21
20
71,976,735
2022-4-23
https://stackoverflow.com/questions/71976735/running-djangos-collectstatic-in-dockerfile-produces-empty-directory
I'm trying to run Django from a Docker container on Heroku, but to make that work, I need to run python manage.py collectstatic during my build phase. To achieve that, I wrote the following Dockerfile: # Set up image FROM python:3.10 WORKDIR /usr/src/app ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 # Install po...
You are overriding the content of /usr/src/app in your container when you added the volumes: - .:/usr/src/app to your docker compose file. Remove it since you already copied everything during the build.
4
5
71,969,496
2022-4-22
https://stackoverflow.com/questions/71969496/can-i-reduce-a-tuple-list-by-key-using-python
I am currently working on showing some visuals about how my NER model has performed. The data I currently have looks like this: counter_list = [ ('Name', {'p':0.56,'r':0.56,'f':0.56}), ('Designation', {'p':0.10,'r':0.20,'f':0.14}), ('Location', {'p':0.56,'r':0.56,'f':0.56}), ('Name', {'p':0.14,'r':0.14,'f':0.14}), ('De...
Why not use pandas and its ~.groupby method? >>> import pandas as pd >>> keys, data = zip(*counter_list) >>> df = pd.DataFrame(data=data, index=keys).groupby(level=0).sum() >>> df p r f Designation 0.20 0.40 0.28 Location 1.12 1.12 1.12 Name 0.70 0.70 0.70 and then do >>> list(df.T.to_dict().items()) [ ('Designation',...
5
3
72,018,887
2022-4-26
https://stackoverflow.com/questions/72018887/how-to-build-a-universal-wheel-with-pyproject-toml
This is the project directory structure . ├── meow.py └── pyproject.toml 0 directories, 2 files This is the meow.py: def main(): print("meow world") This is the pyproject.toml: [build-system] requires = ["setuptools"] build-backend = "setuptools.build_meta" [project] name = "meowpkg" version = "0.1" description = "a ...
Add this section into the pyproject.toml: [tool.distutils.bdist_wheel] universal = true
15
15
71,950,802
2022-4-21
https://stackoverflow.com/questions/71950802/flask-cors-work-only-for-first-request-whats-the-bug-in-my-code
background There is a JS app serving at 127.0.0.1:8080, which refers some API serving at 127.0.0.1:5000 by a Flask app. [See FlaskCode] When I open this js app in Chrome, first request work well and the second request ends with CORS problem, [see ChromeDebug1]. Additionally, I found this 'OPTIONS' is response as 405...
I was getting a similar error: param1=value1&param2=value2GET /css/base.css HTTP/1.1 where the leading params are from a POST request called just before. Setting threaded=False (as @david-k-hess suggested) helped. The whole story was: Browser submits a form using POST Flask server responds with a web page The web page...
4
4
72,018,351
2022-4-26
https://stackoverflow.com/questions/72018351/compare-two-images-and-find-all-pixel-coordinates-that-differ
I have designed a program that compares two images and gives you the coordinates of the pixels that are different in both images and plots the using pygame. I do not mind having to use another library or to remake my whole code but it should ideally take less that 0.6s to process and it should not reduce file size, all...
You do not need to use for loop to do the same. Numpy makes things simple: it's easy to understand speed up operations Reading both your images in grayscale: img1 = cv2.imread(r'C:\Users\524316\Desktop\Stack\m1.png', 0) 1mg2 = cv2.imread(r'C:\Users\524316\Desktop\Stack\m2.png', 0) Subtracting them. cv2.subtract() ta...
4
3
72,012,784
2022-4-26
https://stackoverflow.com/questions/72012784/apply-a-filter-to-an-automatically-joined-table
Here's my SQL setup create table a ( id serial primary key, ta text ); create table b ( id serial primary key, tb text, aid integer references a(id) not null ); Python: import sqlalchemy as sa import sqlalchemy.orm connection_url = "..." engine = sa.create_engine(connection_url, echo=True, future=True) mapper_registr...
The two solutions (for 2 asked questions) presented below rely on two sqlalchemy functions: sqlalchemy.orm.contains_eager to trick sqlalchemy that the desired relationship is already part of the query; and sqlalchemy.orm.Query.options to disable the default joinedload configured on the relationship. Question 1 SELEC...
6
6
71,996,754
2022-4-25
https://stackoverflow.com/questions/71996754/how-to-enable-django-admin-sidebar-navigation-in-a-custom-view
I have a view inheriting from LoginRequiredMixin, TemplateView, which renders some data using the admin/base_site.html template as the base. I treat it as a part of the admin interface, so it requires an administrator login. I'd like to make this view a little bit more a part of the Django admin interface by enabling t...
By accident I noticed there is a DefaultAdminSite object in django.contrib.admin.sites, and it's instantiated as site. Therefore, in my case, simply using site is sufficient. from django.contrib.admin import AdminSite from django.contrib.admin.sites import site admin_site: AdminSite = site data.update(**admin_site.each...
8
6
72,011,315
2022-4-26
https://stackoverflow.com/questions/72011315/permissionerror-winerror-32-the-process-cannot-access-the-file-because-it-is
I installed python-certifi-win32 package and after that, I am getting below error, when I import anything or pip install anything, the fail with the final error of PermissionError. I tried rebooting the box. It didn't work. I am unable to uninstall the package as pip is erroring out too. I am unable to figure out the e...
I ran into the same issue today. I corrected it by removing two *.pth files that were created when I had installed python-certifi-win32. This prevents python-certifi-win32 from loading when python is run. The files are listed below, and were located here: C:\Users\<username>\AppData\Local\Programs\Python\Python310\Lib\...
14
32
72,017,146
2022-4-26
https://stackoverflow.com/questions/72017146/how-to-get-all-fuzzy-matching-substrings-between-two-strings-in-python
Say I have three example strings text1 = "Patient has checked in for abdominal pain which started 3 days ago. Patient was prescribed idx 20 mg every 4 hours." text2 = "The time of discomfort was 3 days ago." text3 = "John was given a prescription of idx, 20mg to be given every four hours" If I got all the matching sub...
Here is a code to calculate the similarity by fuzzy ratio between the sub-string of string1 and full-string of string2. The code can also handle sub-string of string2 and full-string of string1 and also sub-string of string1 and sub-string of string2. This one uses nltk to generate ngrams. Typical algorithm: Generate ...
5
7
72,003,987
2022-4-25
https://stackoverflow.com/questions/72003987/pydantic-checking-if-list-field-is-unique
Currently, I am trying to create a pydantic model for a pandas dataframe. I would like to check if a column is unique by the following import pandas as pd from typing import List from pydantic import BaseModel class CustomerRecord(BaseModel): id: int name: str address: str class CustomerRecordDF(BaseModel): __root__: L...
You could use an inner function and the allow_reuse argument: def root_unique_validator(field): def validator(cls, values): # Use the field arg to validate a specific field ... return root_validator(pre=True, allow_reuse=True)(validator) Full example: import pandas as pd from typing import List from pydantic import Ba...
5
1
71,937,745
2022-4-20
https://stackoverflow.com/questions/71937745/python-closest-match-between-two-string-columns
I am looking to get the closest match between two columns of string data type in two separate tables. I don't think the content matters too much. There are words that I can match by pre-processing the data (lower all letters, replace spaces and stop words, etc...) and doing a join. However I get around 80 matches out o...
Here is an answer I finally got: from fuzzywuzzy import process, fuzz value = [] similarity = [] for i in df1.col: ratio = process.extract(i, df2.col, limit= 1) value.append(ratio[0][0]) similarity.append(ratio[0][1]) df1['value'] = pd.Series(value) df1['similarity'] = pd.Series(similarity) This will add the value wit...
4
2