content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
Python setuptools-scm producing version with .dev, unable to upload to PyPi
When / Why does setuptools-scm append .devXXX to its generated version?
In a couple repos I maintain setuptools-scm starts producing versions with .devXXX appended to the version number. This causes issues because this tag is invalid for u... | Python setuptools-scm producing version with .dev, unable to upload to PyPi | When / Why does setuptools-scm append .devXXX to its generated version?
In a couple repos I maintain setuptools-scm starts producing versions with .devXXX appended to the version number. This causes issues because this tag is invalid for upload to PyPi.
I created a workaround the first time this happened, and I assumed... | [
"It's doing so because commits not tagged have their version value computed like this:\nX.Y.(Z+1)-devN-gSHA\nwhere:\nX.Y.Z is the most recent previous tagged commit on top of/above which you are actually.\nN is the number of commits you are after that previous X.Y.Z\nand SHA is the SHA of your current commit.\n-dev... | [
0
] | [] | [] | [
"continuous_integration",
"python",
"setuptools",
"setuptools_scm"
] | stackoverflow_0073157896_continuous_integration_python_setuptools_setuptools_scm.txt |
Q:
How to add a new column into an existing DataFrame?
I am trying to add a synthetic data column to the existing the movies dataset. This new column is the gross revenue of an actor's second most recent movie.
For example:
Movie
Actor
Revenue
New Column*
A
Nic Cage
$7
$5
B
Nic Cage
$6
$4
C
Nic Cage
$5
-
D
Nic C... | How to add a new column into an existing DataFrame? | I am trying to add a synthetic data column to the existing the movies dataset. This new column is the gross revenue of an actor's second most recent movie.
For example:
Movie
Actor
Revenue
New Column*
A
Nic Cage
$7
$5
B
Nic Cage
$6
$4
C
Nic Cage
$5
-
D
Nic Cage
$4
-
E
Al Pacino
$3
$1
F
Al Pacino
$2
-
... | [
"Assuming the movies are sorted, use groupby.shift\ndf['New Column'] = df.groupby('Actor')['Revenue'].shift(-2, fill_value='-')\n\nOutput:\n Movie Actor Revenue New Column\n0 A Nic Cage $7 $5\n1 B Nic Cage $6 $4\n2 C Nic Cage $5 -\n3 D Nic Cage ... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074454639_pandas_python.txt |
Q:
Is there a way to sort python grpc response without using jSON?
Long story short I am building a python grpc client that interacts with another team's GRPC server. Does python's grpc module have any sorting features?
response = client_stub.get_grpc_templates_stub(grpc_stub_method).ListTemplateRevisions(request=req... | Is there a way to sort python grpc response without using jSON? | Long story short I am building a python grpc client that interacts with another team's GRPC server. Does python's grpc module have any sorting features?
response = client_stub.get_grpc_templates_stub(grpc_stub_method).ListTemplateRevisions(request=request, metadata=metadata_okta_token_and_env)
grpc_logger.debug(respon... | [
"Python should (!) yield Python lists for protobuf repeated elements and you can sort Python lists and extract specific values.\nSo, assuming your proto is something like:\nsyntax = \"proto3\";\n\npackage foo;\n\nimport \"google/protobuf/timestamp.proto\";\n\nmessage X {\n repeated Revision revisions = 1;\n}\n\nme... | [
0
] | [] | [] | [
"grpc",
"grpc_python",
"python",
"sorting"
] | stackoverflow_0074439960_grpc_grpc_python_python_sorting.txt |
Q:
Python identify if someone entered a door from a video feed
I have an emergency door that individuals should only be exiting from, so I'm trying to think of ways to use computer vision with python to identify if someone entered through it. I've found posted discussing tracking individuals and object detection, but... | Python identify if someone entered a door from a video feed | I have an emergency door that individuals should only be exiting from, so I'm trying to think of ways to use computer vision with python to identify if someone entered through it. I've found posted discussing tracking individuals and object detection, but I can't find anything on entering or exiting a door. Any suggest... | [
"It can be done in different ways. I'll give you few suggestions and you pick up as per your need\n\nFix the camera in a way like only those people, who exit the room will be recorded\nIf you want to save and record those data , you can have ID card detection with matching face\n\nIf you explain it some more deep I... | [
0
] | [] | [] | [
"computer_vision",
"deep_learning",
"python"
] | stackoverflow_0074454625_computer_vision_deep_learning_python.txt |
Q:
Target encoding multiple columns in pandas python
I have the following table.
id col1 col2 col3 col4 target
1 A B A 101 1
2 B B A 191 1
3 A B A 81 0
4 C B C 67 1
5 B C C 3 0
I want to target encode every column except col4.
Expected Output:
e1 e... | Target encoding multiple columns in pandas python | I have the following table.
id col1 col2 col3 col4 target
1 A B A 101 1
2 B B A 191 1
3 A B A 81 0
4 C B C 67 1
5 B C C 3 0
I want to target encode every column except col4.
Expected Output:
e1 e2 e3 target
0.5 0.75 0.667 1
0.5 0.75 ... | [
"update after clarification:\nYou need to use the same approach as in your original attempt, but using map\ndf.update(df[['col1', 'col2', 'col3']]\n .apply(lambda s: s.map(df['target'].groupby(s).mean()))\n )\n\noutput:\n id col1 col2 col3 col4 target\n0 1 0.5 0.75 0.666667 101 ... | [
3,
1,
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0073583250_pandas_python.txt |
Q:
Class_name.apply syntax in python
I am new to object oriented programming and pytorch framework. I am stuck with the usage of syntax shown below:
self. variable_name= some_class_name.apply
It would be great if someone can explain me this kind of syntax.
I tried searching this on various websites but could not fi... | Class_name.apply syntax in python | I am new to object oriented programming and pytorch framework. I am stuck with the usage of syntax shown below:
self. variable_name= some_class_name.apply
It would be great if someone can explain me this kind of syntax.
I tried searching this on various websites but could not find any appropriate solution.
I saw the... | [
"In python, assigning a function or method to a variable means that the assigned variable is a reference of the function or method. For example, we define a function func:\ndef func(x): \n return x**2\n\nand then we assign func to a variable g: g=func. After that, we can directly call the function func by callin... | [
0
] | [] | [] | [
"oop",
"python",
"pytorch"
] | stackoverflow_0074454635_oop_python_pytorch.txt |
Q:
Streamlit real multipage app - Can session.state from select box state synced on all pages?
I'm building a small streamlit app which should show various topics' results through pages. So, on page 1 we have basketball, on page 2 volleyball, etc. Selectbox (dropdown) should be present on each page, allowing the user... | Streamlit real multipage app - Can session.state from select box state synced on all pages? | I'm building a small streamlit app which should show various topics' results through pages. So, on page 1 we have basketball, on page 2 volleyball, etc. Selectbox (dropdown) should be present on each page, allowing the user to switch countries. Is there a way for when the user selects the country on i.e. basketball pag... | [
"The selectbox has an index parameter to represent the value that will be shown in the box. We can use it to update the box. We will use session state to update the index in all pages. The country value is already tracked by st.session_state.country.\nmain.py\nimport streamlit as st\n\nif 'index' not in st.session_... | [
1
] | [] | [] | [
"multi_page_application",
"python",
"streamlit"
] | stackoverflow_0074450493_multi_page_application_python_streamlit.txt |
Q:
Celery soft time limit not triggered
I have a celery task with a soft limit of 10 and hard limit of 32:
from celery.exceptions import SoftTimeLimitExceeded
from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import get_project_settings
@app.task(bind=True, acks_late=False, time_limit=32, soft_time... | Celery soft time limit not triggered | I have a celery task with a soft limit of 10 and hard limit of 32:
from celery.exceptions import SoftTimeLimitExceeded
from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import get_project_settings
@app.task(bind=True, acks_late=False, time_limit=32, soft_time_limit=10)
def my_task(self, **kwargs):
... | [
"the same issue happened in my side.\nI think the most possible is \"SoftTimeLimitExceeded\" error catch in your script. so it do not raise to the outside.\nyou can check if there are any Exception expect in your script and remove them or just replace to small scope Exception.\n settings = get_project_settings()\n ... | [
0
] | [] | [] | [
"celery",
"exception",
"python",
"scrapy",
"taskmanager"
] | stackoverflow_0074289118_celery_exception_python_scrapy_taskmanager.txt |
Q:
Cleanest way to hide every nth tick label in matplotlib colorbar?
The labels on my horizontal colorbar are too close together and I don't want to reduce text size further:
cbar = plt.colorbar(shrink=0.8, orientation='horizontal', extend='both', pad=0.02)
cbar.ax.tick_params(labelsize=8)
I'd like to preserve all t... | Cleanest way to hide every nth tick label in matplotlib colorbar? | The labels on my horizontal colorbar are too close together and I don't want to reduce text size further:
cbar = plt.colorbar(shrink=0.8, orientation='horizontal', extend='both', pad=0.02)
cbar.ax.tick_params(labelsize=8)
I'd like to preserve all ticks, but remove every other label.
Most examples I've found pass a ... | [
"For loop the ticklabels, and call set_visible():\nfor label in cbar.ax.xaxis.get_ticklabels()[::2]:\n label.set_visible(False)\n\n",
"One-liner for those who are into that!\nn = 7 # Keeps every 7th label\n[l.set_visible(False) for (i,l) in enumerate(ax.xaxis.get_ticklabels()) if i % n != 0]\n\n",
"Just cam... | [
87,
22,
13,
5,
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0020337664_matplotlib_python.txt |
Q:
Confused on how to read values from JSON file into Python script
Here is my JSON file:
{
"credentials":
{
"server": "0.1.2.3,6666",
"database": "db",
"username": "user",
"password": "password"
}
}
Here is my python script in a separate file:
import pandas as pd
import datatest as dt
import da... | Confused on how to read values from JSON file into Python script | Here is my JSON file:
{
"credentials":
{
"server": "0.1.2.3,6666",
"database": "db",
"username": "user",
"password": "password"
}
}
Here is my python script in a separate file:
import pandas as pd
import datatest as dt
import datetime
import json
import pyodbc
with open(r"path_to_config.json", '... | [
"not sure what version of python you are using, but you can load your json into a dict and build the connection string from that.\nSomething like:\nwith open(\"path_to_config.json\") as cfgfile:\n df = json.load(cfgfile)\n\ndriver = (\n 'DRIVER={ODBC Driver 17 for SQL Server};'\n f\"SERVER='{df['credential... | [
0
] | [] | [] | [
"json",
"python"
] | stackoverflow_0074454552_json_python.txt |
Q:
Permission System for Discord.py Bot
I am in the process of making a discord bot using discord.py and asyncio. The bot has commands like kick and ban which obviously should not be available to normal users.
I want to make a simple system which will detect what permissions the user's role has using ctx.message.auth... | Permission System for Discord.py Bot | I am in the process of making a discord bot using discord.py and asyncio. The bot has commands like kick and ban which obviously should not be available to normal users.
I want to make a simple system which will detect what permissions the user's role has using ctx.message.author to get the user who sent the command.
I... | [
"Permissions is the name of the class. To get the message authors permissions, you should access the guild_permissions property of the author.\nif ctx.message.author.guild_permissions.administrator:\n # you could also use guild_permissions.kick_members\n\nUpdate:\nA better way to validate the permissions of the pe... | [
17,
5,
1,
0
] | [] | [] | [
"discord",
"discord.py",
"python",
"python_3.x",
"python_asyncio"
] | stackoverflow_0048612603_discord_discord.py_python_python_3.x_python_asyncio.txt |
Q:
python: converting numbers to words
I'm trying to write a code that will convert numbers to words, up to 999 trillion. here is my code so far. it works up to 119, but after that things get messy. I can't use append or enumerate. I'm stuck on how to print the larger numbers; how would I format a number like 978,674... | python: converting numbers to words | I'm trying to write a code that will convert numbers to words, up to 999 trillion. here is my code so far. it works up to 119, but after that things get messy. I can't use append or enumerate. I'm stuck on how to print the larger numbers; how would I format a number like 978,674,237,105?
NUMBERS = ["zero", "one", "two"... | [
"This can easily be done recursively:\ndef as_words(n):\n \"\"\"Convert an integer n (+ve or -ve) to English words.\"\"\"\n # lookups\n ones = ['zero', 'one', 'two', 'three', 'four',\n 'five', 'six', 'seven', 'eight', 'nine', \n 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen',\n ... | [
3,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0024109866_python.txt |
Q:
Generate a heatmap using a scatter data set
I have a set of X,Y data points (about 10k) that are easy to plot as a scatter plot but that I would like to represent as a heatmap.
I looked through the examples in Matplotlib and they all seem to already start with heatmap cell values to generate the image.
Is there a ... | Generate a heatmap using a scatter data set | I have a set of X,Y data points (about 10k) that are easy to plot as a scatter plot but that I would like to represent as a heatmap.
I looked through the examples in Matplotlib and they all seem to already start with heatmap cell values to generate the image.
Is there a method that converts a bunch of x, y, all differe... | [
"If you don't want hexagons, you can use numpy's histogram2d function:\nimport numpy as np\nimport numpy.random\nimport matplotlib.pyplot as plt\n\n# Generate some test data\nx = np.random.randn(8873)\ny = np.random.randn(8873)\n\nheatmap, xedges, yedges = np.histogram2d(x, y, bins=50)\nextent = [xedges[0], xedges[... | [
221,
120,
65,
36,
33,
25,
10,
5,
2,
2,
2,
1,
0
] | [] | [] | [
"heatmap",
"histogram2d",
"matplotlib",
"python"
] | stackoverflow_0002369492_heatmap_histogram2d_matplotlib_python.txt |
Q:
I am installing requirement.txt getting the error EnvironmentLocationNotFound: Not a conda environment: C:\Users\nmyle\anaconda3\envs\requirements.txt
I am installing a requirements.txt in Visual studio code for windows. I type in the terminal in visual studio code conda activate py310. Everything works fine. Then... | I am installing requirement.txt getting the error EnvironmentLocationNotFound: Not a conda environment: C:\Users\nmyle\anaconda3\envs\requirements.txt | I am installing a requirements.txt in Visual studio code for windows. I type in the terminal in visual studio code conda activate py310. Everything works fine. Then I type conda install -n requirements.txt and get the error EnvironmentLocationNotFound: Not a conda environment: C:\Users\nmyle\anaconda3\envs\requirements... | [
"Looks like a typo. The --name,-n argument is string to name the resulting environment, whereas the --file argument is a requirements.txt file. So, instead want something like\nconda create -n foo --file requirements.txt\n\nwhere \"foo\" would be the name of the new environment.\n"
] | [
1
] | [] | [] | [
"anaconda",
"conda",
"python",
"visual_studio_code"
] | stackoverflow_0074452489_anaconda_conda_python_visual_studio_code.txt |
Q:
I'm getting an error on line 8 that "V" is undefined, despite defining in line 4. Thoughts?
import math
float(input("C"))
#c="speed of light" in m/s
float(input("V"))
#v="speed of mobile" in m/s
float(input("M"))
#m="mass of mobile" in Kg
1/math.sqrt((1-V/C)^2)==Gam2
print(Gam)
M*V==p
M*V*Gam==q
I checked the ca... | I'm getting an error on line 8 that "V" is undefined, despite defining in line 4. Thoughts? | import math
float(input("C"))
#c="speed of light" in m/s
float(input("V"))
#v="speed of mobile" in m/s
float(input("M"))
#m="mass of mobile" in Kg
1/math.sqrt((1-V/C)^2)==Gam2
print(Gam)
M*V==p
M*V*Gam==q
I checked the capitalization of the input float of "V", and they still match up, but I'm still getting an error.
| [
"I took the problem you had:\nimport math \nC = float(input(\"C\"))\n#c=\"speed of light\" in m/s\nV = float(input(\"V\"))\n#v=\"speed of mobile\" in m/s\nM = float(input(\"M\"))\n#m=\"mass of mobile\" in Kg\nGam = 1 / math.sqrt(math.pow(1 - V / C, 2))\nprint(Gam)\np = M * V\nq = M * V * Gam \n\nhad to define all b... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074454801_python.txt |
Q:
How to use slider with plotly in order to show figure from begging to current step?
I want to use plotly to show 2 sinuse waves
I want to use slider to show the progress from time=0 to current slider step.
I tried to write the following code:
import numpy as np
import pandas as pd
if __name__ == "__main__":
... | How to use slider with plotly in order to show figure from begging to current step? |
I want to use plotly to show 2 sinuse waves
I want to use slider to show the progress from time=0 to current slider step.
I tried to write the following code:
import numpy as np
import pandas as pd
if __name__ == "__main__":
time = np.arange(0, 10, 0.1)
val1 = np.sin(time)
val2 = np.sin(time) *... | [
"I don't think it is possible to animate a line chart in Express, so I would have to use a graph object. There is an example in the reference, which I will adapt to your assignment. As for the graph structure, create the initial graph data and the respective frames in the animation, add them to the layout by creati... | [
1
] | [] | [] | [
"plotly",
"plotly_dash",
"python",
"python_3.x"
] | stackoverflow_0074445829_plotly_plotly_dash_python_python_3.x.txt |
Q:
What is difference between plot and iplot in Pandas?
What is the difference between plot() and iplot() in displaying a figure in Jupyter Notebook?
A:
I just started using iplot() in Python (3.6.6). I think it uses the Cufflinks wrapper over plotly that runs Matplotlib under the hood. It is seems to be the easies... | What is difference between plot and iplot in Pandas? | What is the difference between plot() and iplot() in displaying a figure in Jupyter Notebook?
| [
"I just started using iplot() in Python (3.6.6). I think it uses the Cufflinks wrapper over plotly that runs Matplotlib under the hood. It is seems to be the easiest way for me to get interactive plots with simple one line code.\nAlthough it needs some libraries to setup. For example, the code below works in Jupyte... | [
9,
7,
1,
0
] | [] | [] | [
"matplotlib",
"pandas",
"plotly",
"python"
] | stackoverflow_0049880314_matplotlib_pandas_plotly_python.txt |
Q:
Most efficient way to split substrings into individual words
I have several strings that I want to loop through and tokenize
ImagesCarrier FreeCatalog #AvailabilitySize / PriceQty240-B-001MG/CF240-B-002/CF240-B-010/CF240-B-500/CFWith CarrierCatalog #AvailabilitySize / PriceQty240-B-002240-B-010Request a Quote
All... | Most efficient way to split substrings into individual words | I have several strings that I want to loop through and tokenize
ImagesCarrier FreeCatalog #AvailabilitySize / PriceQty240-B-001MG/CF240-B-002/CF240-B-010/CF240-B-500/CFWith CarrierCatalog #AvailabilitySize / PriceQty240-B-002240-B-010Request a Quote
All of the string splitting methods I have used so far give me an out... | [
"You can use lookarounds:\nre.sub(r'(?<=\\S)(?=[A-Z][a-z])|(?<=[A-Za-z])(?=\\d)', ' ', s)\n\nDemo: https://replit.com/@blhsing/DownrightTwinTelephones\n"
] | [
2
] | [] | [] | [
"python",
"regex",
"string"
] | stackoverflow_0074454701_python_regex_string.txt |
Q:
what is activate file in flask and what are other activate.bat activate.ps1 and others
I am new to flask, in some tutorial i saw using something like /Scripts/activate in linux and in other tutorial i saw /Scripts/activate.ps1 what are those activate.ps1 activate.bat and how they differ from activate file.
are all... | what is activate file in flask and what are other activate.bat activate.ps1 and others | I am new to flask, in some tutorial i saw using something like /Scripts/activate in linux and in other tutorial i saw /Scripts/activate.ps1 what are those activate.ps1 activate.bat and how they differ from activate file.
are all those only for activating environment but in different way?
| [
"That's the typical script to activate a conda or venv environment. Best practice is to create a virtual environment (e.g., with conda or venv) specifically for each project, to avoid conflicts, and then activate that environment just before using it.\nOn Linux, the path is normally bin/activate, while Scripts\\act... | [
2
] | [] | [] | [
"python",
"virtualenv"
] | stackoverflow_0074454909_python_virtualenv.txt |
Q:
I have a problem accessing csv file in jupyter notebook with python
Hi I have a beginner problem. So I wanted to access csv file with jupyter notebook and I am using python. I am opening the jupyter notebook on visual studio code. So here is my code
import pandas as pd
df3 = pd.read_csv("D:/medali.csv")
imax = df3... | I have a problem accessing csv file in jupyter notebook with python | Hi I have a beginner problem. So I wanted to access csv file with jupyter notebook and I am using python. I am opening the jupyter notebook on visual studio code. So here is my code
import pandas as pd
df3 = pd.read_csv("D:/medali.csv")
imax = df3["bronze"].idxmax()
df3[imax:imax+1]
The thing is I kept stuck with the ... | [
"The easiest thing to do, assuming you're on windows os, is to go to the file, right click, select \"copy as file path\", and then put that in the place of \"D:/medali.csv\". That should fix the issue, but you may find that you also have to set the file path string as a raw string to keep it from being messed up by... | [
0
] | [] | [] | [
"csv",
"jupyter_notebook",
"python"
] | stackoverflow_0074454897_csv_jupyter_notebook_python.txt |
Q:
move/translate values of 2d array by a specific amount (up)
I would like to understand various 2d array translation approaches.
I have a method which returns a list of (x, y) coordinate indexes corresponding to values that should be deleted in the 2d array. Values below should take the place of the value to be del... | move/translate values of 2d array by a specific amount (up) | I would like to understand various 2d array translation approaches.
I have a method which returns a list of (x, y) coordinate indexes corresponding to values that should be deleted in the 2d array. Values below should take the place of the value to be deleted, and values below that, should be moved into their's place, ... | [
"Note: the coordinates that you used are inverted. Numpy indexing would be (row, col) where you use (col, row). The solution below uses transposition to adapt to your coordinates.\nI would craft a boolean mask to identify the positions to delete/shift. Then use argsort to push the True values to the end and use the... | [
0
] | [] | [] | [
"arrays",
"multidimensional_array",
"numpy",
"numpy_ndarray",
"python"
] | stackoverflow_0074454747_arrays_multidimensional_array_numpy_numpy_ndarray_python.txt |
Q:
Scrapy: Get Start_Urls from Database by Pipeline
Unfortunately I don't have enough population to make a comment, so I have to make this new question, referring to https://stackoverflow.com/questions/23105590/how-to-get-the-pipeline-object-in-scrapy-spider
I have many urls in a DB. So I want to get the start_url fr... | Scrapy: Get Start_Urls from Database by Pipeline | Unfortunately I don't have enough population to make a comment, so I have to make this new question, referring to https://stackoverflow.com/questions/23105590/how-to-get-the-pipeline-object-in-scrapy-spider
I have many urls in a DB. So I want to get the start_url from my db. So far not a big problem.
Well I don't want ... | [
"Scrapy pipelines already have expected methods of open_spider and close_spider \nTaken from docs: https://doc.scrapy.org/en/latest/topics/item-pipeline.html#open_spider\n\nopen_spider(self, spider)\n This method is called when the spider is opened.\n Parameters: spider (Spider object) – the spider which was o... | [
1,
1
] | [] | [] | [
"python",
"scrapy"
] | stackoverflow_0046339263_python_scrapy.txt |
Q:
How can I use subprocess.run() in a detached process
In a python script, I want to call subprocess.run() multiple times with varying arguments. While this initially works fine from the cli, it fails when the script is detached from the shell, eg with script.py &
As an example, lets transcode a folder of .wav files... | How can I use subprocess.run() in a detached process | In a python script, I want to call subprocess.run() multiple times with varying arguments. While this initially works fine from the cli, it fails when the script is detached from the shell, eg with script.py &
As an example, lets transcode a folder of .wav files.
from glob import glob
import subprocess as sp
for w in ... | [
"While I was unable to find a solution on the web, I did find an option to make this work, so I am documenting it here for others.\nEnabling start_new_session was the solution for me, this is a Popen option that gets passed on in the underlying code.\nfrom glob import glob\nimport subprocess as sp\n\nfor w in sorte... | [
0
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0074455029_python_subprocess.txt |
Q:
How to group data based on criteria and fill down values
I'm trying to group values of below list in a dataframe based on Style,Gender and Region but with
values filled down.
My cuurent attempt gets a dataframe without style and region filled down. Not sure if it is good approach or would better
to manipulate the ... | How to group data based on criteria and fill down values | I'm trying to group values of below list in a dataframe based on Style,Gender and Region but with
values filled down.
My cuurent attempt gets a dataframe without style and region filled down. Not sure if it is good approach or would better
to manipulate the list lst
import pandas as pd
lst = [
['Tee','Boy','Ea... | [
"You just need to use reset_index that will reset back to normal\ndf2.reset_index(inplace=True)\n\n"
] | [
1
] | [] | [] | [
"dataframe",
"group_by",
"python"
] | stackoverflow_0074454275_dataframe_group_by_python.txt |
Q:
Pandas rolling by date interval returning wrong result
I have this data:
data = {
'id': [1, 2, 3, 4, 5, 6],
'number': [2, 3, 5, 6, 7, 8],
'date': ['2010-01-01', '2010-01-01', '2020-01-04', '2020-01-04', '2020-01-04', '2020-01-05']
}
df = pd.DataFrame(data)
I need to get the mean of col number in the last 1... | Pandas rolling by date interval returning wrong result | I have this data:
data = {
'id': [1, 2, 3, 4, 5, 6],
'number': [2, 3, 5, 6, 7, 8],
'date': ['2010-01-01', '2010-01-01', '2020-01-04', '2020-01-04', '2020-01-04', '2020-01-05']
}
df = pd.DataFrame(data)
I need to get the mean of col number in the last 1 day.
df.index = pd.to_datetime(df['date'])
df['mean_number'... | [
"Try:\ndf['mean_number'] = df['number'].rolling('1D', closed='left').mean()\n\nResult:\n id number date mean_number\ndate \n2010-01-01 1 2 2010-01-01 NaN\n2010-01-01 2 3 2010-01-01 2.0\n2020-01-04 3 5 2020-01-... | [
1
] | [] | [] | [
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074454225_pandas_python_python_3.x.txt |
Q:
FastApi 422 Unprocessable Entity, on authentication, how to fix?
Cannot understand even if i delete all inside function and just print something still got this error, but when i use fastapi docs, and try signing with that, it work.
@auth_router.post('/signin')
async def sign_in(username: str = Form(...), password:... | FastApi 422 Unprocessable Entity, on authentication, how to fix? | Cannot understand even if i delete all inside function and just print something still got this error, but when i use fastapi docs, and try signing with that, it work.
@auth_router.post('/signin')
async def sign_in(username: str = Form(...), password: str = Form(...)) -> dict:
user = await authenticate_user(username... | [
"Although you did not publish the error, who's purpose is to tell you the problem, I'm fairly sure the problem lies in the way you perform the request.\nThe line\nxhr.setRequestHeader('Content-Type', 'application/json')\n\nmeans that you are sending json data, which is not accepted by the authentication form of ope... | [
4,
0
] | [] | [] | [
"fastapi",
"javascript",
"python"
] | stackoverflow_0067469367_fastapi_javascript_python.txt |
Q:
SUM() giving error 'dict object' has no attribute 'SUM'
My query {{ SUM(something) }} is giving an error.
HTML :
{% for stock in portfolio %}
<tr>
<td>{{ stock.symbol }}</td>
<td>{{ stock.name }}</td>
<td>{{ "stock.SUM(shares)" }}</td>
<td... | SUM() giving error 'dict object' has no attribute 'SUM' | My query {{ SUM(something) }} is giving an error.
HTML :
{% for stock in portfolio %}
<tr>
<td>{{ stock.symbol }}</td>
<td>{{ stock.name }}</td>
<td>{{ "stock.SUM(shares)" }}</td>
<td>{{ stock.price }}</td>
<td>{{ stock.SUM(tota... | [
"I was able to solve this by the following syntax:\n<td>{{ stock['SUM(shares)'] }}</td>\n<td>{{ stock['SUM(total)'] }}</td>\n\nThe 'dict object' error hinted that maybe a dict syntax could work, and it did.\n"
] | [
0
] | [] | [] | [
"flask",
"jinja2",
"python",
"sqlite"
] | stackoverflow_0074454921_flask_jinja2_python_sqlite.txt |
Q:
FastApi: 422 Unprocessable Entity
I'm getting this error while trying to accept a pedantic model. After debugging for quite some time I believe the problem is with accepting CodeCreate
Pydantic model
class BaseCode(BaseModel):
index: Optional[int] = Field(None)
email: EmailStr
gen_time: datetime
ex... | FastApi: 422 Unprocessable Entity | I'm getting this error while trying to accept a pedantic model. After debugging for quite some time I believe the problem is with accepting CodeCreate
Pydantic model
class BaseCode(BaseModel):
index: Optional[int] = Field(None)
email: EmailStr
gen_time: datetime
expire_time: datetime
class CodeCreate(... | [
"The 422 Unprocessable Entity error because of ContentType is incorrect. The FastAPI/Pydantic need ContentType = application/json to parse request body.\nAre you sure your POST request has ContentType header is application/json?\nIf not add it!\n",
"According to MDN\nhere,\na 422 Unprocessable Entity means that t... | [
1,
0,
0,
0,
-1
] | [] | [] | [
"fastapi",
"http_status_code_422",
"pydantic",
"python"
] | stackoverflow_0070828763_fastapi_http_status_code_422_pydantic_python.txt |
Q:
How to convert a line in csv to a list of objects
Each line in my csv file is data on a pet. Ex"Fish, Nemo, April 2nd, Goldfish, Orange." I would like to import that file and create a new object for that pet depending on its type(the first string in each line). For example data about the fish would be stored in a ... | How to convert a line in csv to a list of objects | Each line in my csv file is data on a pet. Ex"Fish, Nemo, April 2nd, Goldfish, Orange." I would like to import that file and create a new object for that pet depending on its type(the first string in each line). For example data about the fish would be stored in a fish object. I then want to put each object into a list... | [
"With csv.DictReader you can accomplish what your current code attempts by specifying fieldnames and assuming your \"object\" desired is a dictionary:\npets.csv\nFish,Nemo,April 2nd,Goldfish,Orange\nCat,Garfield,June 1st,Tabby,Orange\n\ntest.py\nimport csv\nfrom pprint import pprint\n\nwith open('pets.csv', newline... | [
0
] | [] | [] | [
"class",
"csv",
"list",
"object",
"python"
] | stackoverflow_0074455014_class_csv_list_object_python.txt |
Q:
Can't always detect last date in python
I have some code created in python and I need it to always detect the last date of the JSON of the fortnite API, how can I do it?
response = requests.get("https://fortnite-api.com/v2/cosmetics/br/search/all?language=es&name=palito%20de%20pescado%20de%20gominola&searchLangua... | Can't always detect last date in python | I have some code created in python and I need it to always detect the last date of the JSON of the fortnite API, how can I do it?
response = requests.get("https://fortnite-api.com/v2/cosmetics/br/search/all?language=es&name=palito%20de%20pescado%20de%20gominola&searchLanguage=es")
fecha = isoparse(response.json()['... | [
"Api gives list of date strings. You can try this:\nimport requests, time\nimport dateutil.parser as dp\n\nresponse = requests.get(\"https://fortnite-api.com/v2/cosmetics/br/search/all?language=es&name=palito%20de%20pescado%20de%20gominola&searchLanguage=es\")\n\nlss = response.json()['data'][0]['shopHistory']\n\nl... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074453729_python.txt |
Q:
jenkins injects global environment variables into the container, causing environment variable conflicts when python is executed in the container
This is my jenkinfile
stage('Build') {
agent {
docker {
label '1.63slave'
image 'linux-c4702-image'
... | jenkins injects global environment variables into the container, causing environment variable conflicts when python is executed in the container | This is my jenkinfile
stage('Build') {
agent {
docker {
label '1.63slave'
image 'linux-c4702-image'
args '-u root:root'
}
}
when {
expression {params.build == 'yes'}
... | [
"You can prepend an environment variable definition in front of a commands:\nWORKSPACE=\"${env.WORKSPACE}/boot_images\" python <script.py> <arguments...>\n\nwill set that environment variable just for that command.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074454941_python.txt |
Q:
Anaconda python environment disappeared from VS code
Used to be able to use anaconda python in VS code (ubuntu 20.04). Now the VS code option for Conda environments disappeared and I'm not sure why. Reloading the VS code/rebooting the computer sometimes gives me back the conda environment. But it will disappear ag... | Anaconda python environment disappeared from VS code | Used to be able to use anaconda python in VS code (ubuntu 20.04). Now the VS code option for Conda environments disappeared and I'm not sure why. Reloading the VS code/rebooting the computer sometimes gives me back the conda environment. But it will disappear again when I open another .ipynb file.
This happened after m... | [
"Thanks a lot for the comments! Since I want to use the anaconda environment, not my current environment, a clean uninstall/reinstall worked for me in the end. I'm using Ubuntu 20.04 and followed the instructions on this Visual Studio Code webpage. Not sure what caused the problem in the beginning, might be some ex... | [
0
] | [] | [] | [
"jupyter_notebook",
"python",
"visual_studio_code"
] | stackoverflow_0074407612_jupyter_notebook_python_visual_studio_code.txt |
Q:
Make the input from string to integer in a defined function
this is my current code, however the the input doesn't change to an integer
can someone help me pls
score = [0,20,40,60,80,100,120]
def validate_credits(input_credits):
try:
input_credits = int(input_credits)
except:
raise ValueE... | Make the input from string to integer in a defined function | this is my current code, however the the input doesn't change to an integer
can someone help me pls
score = [0,20,40,60,80,100,120]
def validate_credits(input_credits):
try:
input_credits = int(input_credits)
except:
raise ValueError('integer required')
if input_credits not in sco... | [
"This is a scoping issue. Consider:\ndef the_function(_the_input):\n _the_input = int('2')\n\nif __name__ == \"__main__\":\n the_input = '1'\n the_function(the_input)\n print(the_input)\n\nWhat do you think the_input will be? '1' or 2?\nOutput is '1'\nHow about a list?\ndef the_function(_the_input):\n ... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074455059_python.txt |
Q:
Jupyter file path autocomplete suggestions within quotes suggests third quote
The autosuggest shows duplicate suggestion, one with quote and another without. Since the quotes are already closed, I want to hide the first two suggestions as selecting them adds a third quote.
A:
This issue is caused by extensions y... | Jupyter file path autocomplete suggestions within quotes suggests third quote | The autosuggest shows duplicate suggestion, one with quote and another without. Since the quotes are already closed, I want to hide the first two suggestions as selecting them adds a third quote.
| [
"This issue is caused by extensions you have many intelliSense extensions.\ntry setting\n\"editor.inlineSuggest.enabled\": false or\n\"python.languageServer\": \"None\"\n"
] | [
0
] | [] | [] | [
"autosuggest",
"jupyter",
"python"
] | stackoverflow_0060521057_autosuggest_jupyter_python.txt |
Q:
how to process and load data after rendering a page in Django
I have a dashboard page with some charts(image_link)
For earning charts data, i'm using some queries but this queries are very heavy and take long time(for example 37 seconds!).
Is exist a way for rendering page(with showing loading animation on charts)... | how to process and load data after rendering a page in Django | I have a dashboard page with some charts(image_link)
For earning charts data, i'm using some queries but this queries are very heavy and take long time(for example 37 seconds!).
Is exist a way for rendering page(with showing loading animation on charts) and after that start taking data process?
| [
"django is for logic, what you need is frontend skills.\nIf you learned one of 'React, Vue, Angular',\nit would be very easy to implement loading animation to your application.\nunfortunately, there is no way for the loader in any backend framework\ninclude django.\n"
] | [
0
] | [] | [] | [
"django",
"python",
"sql"
] | stackoverflow_0074444552_django_python_sql.txt |
Q:
Fast ways of accessing core data (via gdb, external library, etc)
I have a gdb python macro walking through data in a c generated core file.
The macro can take a long time to run. It walks through a list of struct pointers, reading each pointer into a gdb.Value. The majority of the time is spent when the first pie... | Fast ways of accessing core data (via gdb, external library, etc) | I have a gdb python macro walking through data in a c generated core file.
The macro can take a long time to run. It walks through a list of struct pointers, reading each pointer into a gdb.Value. The majority of the time is spent when the first piece of data in that struct is accessed. That is due to the lazy feature ... | [
"\nAre there other ways to analyze core files that may be faster?\n\nA core file is logically just an image of the process in memory at the time the core was created.\nYou can use read() to access the data as fast as your disk allows.\nThe trick is to find where in memory the data you care about was. Once you know ... | [
1
] | [] | [] | [
"c",
"gdb",
"python"
] | stackoverflow_0074449785_c_gdb_python.txt |
Q:
How to install REQUESTS, SELENIUM and SCRAPY in google colaboratory?
people,
How can I install those libraries in google colab, I type the next:
!pip install requests
!pip install beautifulsoup4
!pip install lxml
!pip install selenium
!pip install pillow
!pip install pymongo
!pip install scrapy
but receive the ne... | How to install REQUESTS, SELENIUM and SCRAPY in google colaboratory? | people,
How can I install those libraries in google colab, I type the next:
!pip install requests
!pip install beautifulsoup4
!pip install lxml
!pip install selenium
!pip install pillow
!pip install pymongo
!pip install scrapy
but receive the next error:
ERROR: pip's dependency resolver does not currently take into ac... | [
"You can install those libraries in google colab with %:\n%pip install scrapy\n"
] | [
1
] | [] | [] | [
"google_colaboratory",
"pip",
"python",
"scrapy",
"selenium"
] | stackoverflow_0071475354_google_colaboratory_pip_python_scrapy_selenium.txt |
Q:
Which keyword its talking about? ( parent = dict(globals or (), **vars) TypeError: keywords must be strings)
I am trying to make a dictionary using excel data (key, values) to use that dictionary as context for rendering a .docx file. If I manually insert context= { 'key':'value'} it works but I want the context t... | Which keyword its talking about? ( parent = dict(globals or (), **vars) TypeError: keywords must be strings) | I am trying to make a dictionary using excel data (key, values) to use that dictionary as context for rendering a .docx file. If I manually insert context= { 'key':'value'} it works but I want the context to be a dictionary made up of my excel data, when I tried to do that it shows the error, which is pointing to doc.... | [
"Try:\ndoc.render(context=context)\n\n"
] | [
0
] | [] | [] | [
"jinja2",
"python",
"scripting"
] | stackoverflow_0068960053_jinja2_python_scripting.txt |
Q:
Library and Module Question - Python Beginner
I keep running into a few issues when trying to learn how to use the math module. I don't know if the learning material is out of date or maybe I'm just doing something wrong, but every time an example of the math module being imported is used I can't seem to keep up. ... | Library and Module Question - Python Beginner | I keep running into a few issues when trying to learn how to use the math module. I don't know if the learning material is out of date or maybe I'm just doing something wrong, but every time an example of the math module being imported is used I can't seem to keep up. Does anyone have any tips for using the math module... | [
"Your code:\nfrom math import sqrt\n\nprint(\"Welcome to the Hypotenuse calculator!\")\n\nsideA = float(input(\"Please enter the length of side 'a': \"))\nsideB = float(input(\"Please enter the length of side 'b': \"))\n\nc = sqrt(sideA ** 2 = sideB ** 2)\n\nprint(\"Thank you! The length of the Hypotenuse is \", st... | [
0
] | [] | [] | [
"math",
"module",
"pycharm",
"python"
] | stackoverflow_0074455198_math_module_pycharm_python.txt |
Q:
How to add csv files to a pandas dataframe present in Azure file share using python
I have the following code which displays the csv files present in the folder of Azure file share
from azure.storage.file import FileService
file_service = FileService(account_name='storage_account_name', account_key='key')
genera... | How to add csv files to a pandas dataframe present in Azure file share using python | I have the following code which displays the csv files present in the folder of Azure file share
from azure.storage.file import FileService
file_service = FileService(account_name='storage_account_name', account_key='key')
generator = file_service.list_directories_and_files('path/../..')
for file_or_dir in generator:... | [
"After reproducing from my end, I could able to read the csv files using pd.read_csv(< FileName >). Below is the complete code that worked for me.\nfrom azure.storage.file import FileService\n\nimport pandas as pd\n\nfile_service = FileService(account_name='<ACCOUNT_NAME>', account_key='<ACCOUNT_KEY>')\n\ngen... | [
0
] | [] | [] | [
"azure",
"pandas",
"python"
] | stackoverflow_0074444698_azure_pandas_python.txt |
Q:
Question about operator precedence for in and !=
While writing Python code, I got a result different from what I wanted.
>>> temp = [1]
>>> 1 in temp != 2 in temp
False
>>> (1 in temp) != (2 in temp)
True
>>> ((1 in temp) != 2) in temp
True
My purpose was the second, but I wrote it like the first.
The problem has... | Question about operator precedence for in and != | While writing Python code, I got a result different from what I wanted.
>>> temp = [1]
>>> 1 in temp != 2 in temp
False
>>> (1 in temp) != (2 in temp)
True
>>> ((1 in temp) != 2) in temp
True
My purpose was the second, but I wrote it like the first.
The problem has been solved, but I wonder in what order the first exp... | [
"I believe this is caused by operator chaining.\nIn Python, you can write an expression with two (or more) operators like this:\na < b < c\n\nAnd Python treats this as if you wrote (a < b) and (b < c).\nSo Python is treating your expression\n1 in temp != 2 in temp\n\nAs if you wrote:\n(1 in temp) and (temp != 2) an... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0074455092_python.txt |
Q:
Python find all the words with less than 5 letters in the string in a given text
This code doesn't work right now because I don't know the exact code I should use. I need to print out the number of words containing less than 5 letters.
This is what I've been trying:
text = "It is a long established fact that a rea... | Python find all the words with less than 5 letters in the string in a given text | This code doesn't work right now because I don't know the exact code I should use. I need to print out the number of words containing less than 5 letters.
This is what I've been trying:
text = "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout."
... | [
"Hope this help:\ntext = \"It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.\"\nwords = text.split()\ncount = 0\nfor word in words:\n if len(word) < 5:\n count = count + 1\n\nprint(count)\n\n",
"Here's one simple solution using a... | [
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074455279_list_python.txt |
Q:
Sound wave created by Python gives plays background beats along with notes
I have created a script to play twinkle twinkle litte star with reference to this article (https://towardsdatascience.com/mathematics-of-music-in-python-b7d838c84f72) and created some of my changes. The music plays correctly, but there are ... | Sound wave created by Python gives plays background beats along with notes | I have created a script to play twinkle twinkle litte star with reference to this article (https://towardsdatascience.com/mathematics-of-music-in-python-b7d838c84f72) and created some of my changes. The music plays correctly, but there are some annoying beats in the background. Can some please help how to remove that a... | [
"The signal that you generate has discontinuties at each note transition. Each discontinuity results in a \"pop\" of the speakers. A simple way to fix that is to multiply the array associated with each note by an envelope that rises from 0 to 1 at the beginning and falls from 1 to 0 at the end (i.e. provide an \"a... | [
1
] | [] | [] | [
"audio",
"python",
"scipy",
"wav"
] | stackoverflow_0074454715_audio_python_scipy_wav.txt |
Q:
How I can use pandas to load the data set I imported from sklearn?
import pandas
from sklearn.datasets import load_iris
import pandas as pd
import matplotlib.pyplot as plt
data = load_iris()
Like above, I imported an iris data set from sklearn, and then I want to use pandas to load the dataset to do further work... | How I can use pandas to load the data set I imported from sklearn? | import pandas
from sklearn.datasets import load_iris
import pandas as pd
import matplotlib.pyplot as plt
data = load_iris()
Like above, I imported an iris data set from sklearn, and then I want to use pandas to load the dataset to do further work, what should I do?
I know that pandas can read datasets from excel, csv... | [
"If I'm not mistaken, pandas needs to have the file opened first, so I would recommend using the\nwith open(r\"filepath.ext\", \"r\") as f:\n data = f.read()\n\nand then manipulate that \"data\" variable with the stuff that sklearn's \"load_iris\" function can do, or perhaps other sklearn methods. Unfortunately,... | [
0
] | [] | [] | [
"pandas",
"python",
"scikit_learn"
] | stackoverflow_0074455448_pandas_python_scikit_learn.txt |
Q:
Iterate through list and append new rows to dataframe
I have a list of strings that I want to perform operations on and append to rows in a dataframe. Running these operations on a single string works fine but I am having trouble looping through. The code below returns an empty dataframe and I am not sure why?
col... | Iterate through list and append new rows to dataframe | I have a list of strings that I want to perform operations on and append to rows in a dataframe. Running these operations on a single string works fine but I am having trouble looping through. The code below returns an empty dataframe and I am not sure why?
col_names = ["Version Available", "Newer Version Available"]
... | [
"Is this something you are looking for?\n\ncol_names = [\"Version Available\", \"Newer Version Available\"]\n\ndef my_function(item):\n df = pd.DataFrame(columns=col_names) #initialize data frame\n for x in item:\n querywords = x.split()\n resultwords = [word for word in querywords if word not i... | [
1,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0074455428_python_string.txt |
Q:
Question concerning assigning a new value to the member variable of a class element in the list
Assign a new value to the member variable of a class element in the list. Why do all the member variable values of the class elements in the list change? As you can see, I only changed the value of the member variable o... | Question concerning assigning a new value to the member variable of a class element in the list | Assign a new value to the member variable of a class element in the list. Why do all the member variable values of the class elements in the list change? As you can see, I only changed the value of the member variable of Li [0] , but the value of the member variable of all elements in Li changed.enter image description... | [
"List multiplication just adds references to its existing values. A list has no way of knowing how its objects are constructed and certainly can't make new ones. You could try li =[A(2) for _ in range(3)] to construct your own.\n"
] | [
0
] | [] | [] | [
"class",
"list",
"python"
] | stackoverflow_0074455407_class_list_python.txt |
Q:
How to save JSON object to text file
this is the full code i'm trying to run
from mtcnn.mtcnn import MTCNN
import cv2
image = cv2.imread('figure.jpg')
detector = MTCNN()
face = detector.detect_faces(image)
for face in faces:
print(face)
this is the resulted JSON object:
{'box': [141, 106, 237, 292], 'confiden... | How to save JSON object to text file | this is the full code i'm trying to run
from mtcnn.mtcnn import MTCNN
import cv2
image = cv2.imread('figure.jpg')
detector = MTCNN()
face = detector.detect_faces(image)
for face in faces:
print(face)
this is the resulted JSON object:
{'box': [141, 106, 237, 292], 'confidence': 0.9988177418708801, 'keypoints': {'le... | [
"First to omit box and confidence:\nfaces = faces['keypoints']\n\nThis will give you a JSON object as:\n{'left_eye': (211, 218), 'right_eye': (321, 219), 'nose': (265, 278), 'mouth_left': (209, 319), 'mouth_right': (319, 324)}\n\nThen to write in file:\nwith open(\"result.txt\",\"w\") as result_file:\n for face ... | [
1
] | [] | [] | [
"dictionary",
"json",
"keypoint",
"python",
"tuples"
] | stackoverflow_0074455159_dictionary_json_keypoint_python_tuples.txt |
Q:
grouping data from files into separate dataframes
i am new to coding and trying to apply what I've learned to my work.
I have 7 sales record(by month) files in csv format, which i read by pd.read_csv().
Below is an example of what each file looks like.
Account A
Account B
Account C
product 1
1
2
3
product 2
1
2... | grouping data from files into separate dataframes | i am new to coding and trying to apply what I've learned to my work.
I have 7 sales record(by month) files in csv format, which i read by pd.read_csv().
Below is an example of what each file looks like.
Account A
Account B
Account C
product 1
1
2
3
product 2
1
2
3
product 3
1
2
3
product 4
1
2
3
What... | [
"If you're using a DataFrame, you should be using the pandas module, correct? The DataFrame object is not the best choice for what you're trying to do. In the pandas module, another object class that would work for you is the Series, which is very similar to a DataFrame in that it has headers, but is only 1 row of ... | [
0,
0
] | [] | [] | [
"data_analysis",
"pandas",
"python"
] | stackoverflow_0074454820_data_analysis_pandas_python.txt |
Q:
Logging in Databricks Python Notebooks
Coming from a Java background, I'm missing a global logging framework/configuration for Python Notebooks, like log4j.
In log4j I would configure a log4j configuration file, that sends
logs directy to Azure Log Analytics.
How do I do this in Databricks for Python Notebooks?
I ... | Logging in Databricks Python Notebooks | Coming from a Java background, I'm missing a global logging framework/configuration for Python Notebooks, like log4j.
In log4j I would configure a log4j configuration file, that sends
logs directy to Azure Log Analytics.
How do I do this in Databricks for Python Notebooks?
I would like to call something like: log.warn(... | [
"Configure Databricks to send logs to Azure Log Analytics\nI configure spark cluster to send logs to the Azure log analytics workspace\nSteps to set up the library:\nStep 1: Clone the repository\n\nStep 2: Set Azure Databricks workspace\nStep 3: Install Azure Databricks CLI and set up authentication.\nRun followi... | [
1
] | [] | [] | [
"azure_databricks",
"azure_log_analytics",
"databricks",
"python"
] | stackoverflow_0074401525_azure_databricks_azure_log_analytics_databricks_python.txt |
Q:
My python program is not working properly, i'm not exactly sure why
Firstly, I'm a beginner and I don't speak English very well, so any questions about what I'm trying to say are welcome. I was making a python program that received two numbers, and the program showed the prime numbers between them.
The algorithm t... | My python program is not working properly, i'm not exactly sure why | Firstly, I'm a beginner and I don't speak English very well, so any questions about what I'm trying to say are welcome. I was making a python program that received two numbers, and the program showed the prime numbers between them.
The algorithm takes the numbers, turns them into a list, then divides each number in tha... | [
"Your are adding i multplied by j numbers to array2 instead if (probably?) j numbers. Look at the output.\ndef Find_Primes(smaller_num, bigger_num):\n array = list(range(smaller_num, (bigger_num + 1)))\n array2 = []\n\n\n for i in array:\n #numbers from input\n for j in range(1, i):\n ... | [
0,
0
] | [] | [] | [
"primes",
"python"
] | stackoverflow_0074455266_primes_python.txt |
Q:
tesseract attribute error, how do I fix, need solution
I am trying to train a ML model and need to use tesseract to convert image to text.
before, I was getting the 'tesseract not found error"
but after doing some search here I found out I could add its path in front and that would solve the problem. But not I am... | tesseract attribute error, how do I fix, need solution | I am trying to train a ML model and need to use tesseract to convert image to text.
before, I was getting the 'tesseract not found error"
but after doing some search here I found out I could add its path in front and that would solve the problem. But not I am getting
AttributeError: 'str' object has no attribute 'imag... | [
"image_to_string is a function in pytesseract object but not in str,\nand here is a sample of how to use it:\npytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'\nres = pytesseract.image_to_string(done_cap, lang='eng')[:4]\nprint(res)\n\nfollow-up:make sure your done_cap is an... | [
0
] | [] | [] | [
"python",
"python_tesseract"
] | stackoverflow_0074455632_python_python_tesseract.txt |
Q:
DRF responses me by 403 error when I try to request as a client [Client Credential grant]
In settings.py file I have written this settings:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
),
'DEFAULT_PERMISSION_CLASSES': (
... | DRF responses me by 403 error when I try to request as a client [Client Credential grant] | In settings.py file I have written this settings:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
}
When I call any API with a token ... | [
"Finally solved! The problem was the permission I was using. In fact, the IsAuthenticated permission checks request.user which is None when you are using client credentials grant. Since there's no permission for supporting clien credentials grant in DRF, you must use your own DRF custom permission. This is what I n... | [
6,
0
] | [
"you need to enable tokenAuthentication and run migration to apply changes in auth table DB\nREST_FRAMEWORK = {\n 'DEFAULT_AUTHENTICATION_CLASSES': [\n 'rest_framework.authentication.TokenAuthentication', # <-- And here\n ],\n}\n\nINSTALLED_APPS = [\n ...\n 'rest_framework.authtoken'\n]\n\nHere ... | [
-1
] | [
"django",
"django_rest_framework",
"oauth_2.0",
"python"
] | stackoverflow_0058010166_django_django_rest_framework_oauth_2.0_python.txt |
Q:
The code execution cannot proceed because python37.dll was not found
I have a piece of code in C++ into which I am trying to include the Python.h library in order to manage the GIL (to speed things up). Despite adding the proper includes, libraries and path addresses (I am using Visual Studio 2019), I still obtain... | The code execution cannot proceed because python37.dll was not found | I have a piece of code in C++ into which I am trying to include the Python.h library in order to manage the GIL (to speed things up). Despite adding the proper includes, libraries and path addresses (I am using Visual Studio 2019), I still obtain the following error message:
As far as I know, I correctly added the add... | [
"Are you running this program in release mode? After switching from debug to release, the project properties of debug mode will not be inherited, so it is necessary to reset the project properties.\nYou could also try to place the dll file in the .exe directory or write the dll path into the project properties.\nAt... | [
0
] | [] | [] | [
"c++",
"path",
"python",
"visual_studio"
] | stackoverflow_0074455007_c++_path_python_visual_studio.txt |
Q:
vs code show double suggestion
Sample 1
Sample 2
VS Code intellisense shows double suggestions in python whenever I write.
Is there a setting in VS Code, so I can change them to the normal state?
A:
This is a known issue. Upgrading the Jupyter extension to the pre-release version solved it.
A:
Press Ctrl+Shift... | vs code show double suggestion | Sample 1
Sample 2
VS Code intellisense shows double suggestions in python whenever I write.
Is there a setting in VS Code, so I can change them to the normal state?
| [
"This is a known issue. Upgrading the Jupyter extension to the pre-release version solved it.\n\n",
"Press Ctrl+Shift+X to see if other prompt extensions are installed and python original completion is applied at the same time.\nDisable unwanted prompt extensions can solve it.\n"
] | [
1,
0
] | [] | [] | [
"autosuggest",
"pylance",
"python",
"visual_studio_code"
] | stackoverflow_0074454797_autosuggest_pylance_python_visual_studio_code.txt |
Q:
How to get the first items of a group in dask.DataFrame?
I want to get the first item of each set of different entries of a columns containing IDs. It works with pandas, but not in dask, as I cannot sort with multiple columns and the .head aggregation is not implemented. Is there another way of getting the desired... | How to get the first items of a group in dask.DataFrame? | I want to get the first item of each set of different entries of a columns containing IDs. It works with pandas, but not in dask, as I cannot sort with multiple columns and the .head aggregation is not implemented. Is there another way of getting the desired result?
Here is the mimimal example for pandas, where everyth... | [
"It's likely that the NotImplementedError is raised by .sort_values since right now dask.dataframe only implements sorting on a single column value, see docs.\n",
"The solution is dask.groupby.apply with a function that works on a DataFrame of each group.\nimport dask.dataframe as dd\n\nt2=dd.from_pandas(t,nparti... | [
0,
0
] | [] | [] | [
"dask",
"dask_dataframe",
"dataframe",
"python"
] | stackoverflow_0074411407_dask_dask_dataframe_dataframe_python.txt |
Q:
What are the reasons for using type(obj).method() instead of obj.method()?
I've seen a couple of times methods being called on the type of an object instead of the object itself. What might the reasons for that be, especially with special methods?
Example from documentation:
"For instance, if a class defines a met... | What are the reasons for using type(obj).method() instead of obj.method()? | I've seen a couple of times methods being called on the type of an object instead of the object itself. What might the reasons for that be, especially with special methods?
Example from documentation:
"For instance, if a class defines a method named _getitem_(), and x is an instance of this class, then x[i] is roughly ... | [
"The main reason to do this is to simulate how special methods are looked up implicitly. When you do len(seq), the underlying code is (mostly) equivalent to type(seq).__len__(seq), bypassing the instance itself (preventing someone from assigning to seq.__len__ and changing how len behaves for that instance). If you... | [
3
] | [] | [] | [
"magic_methods",
"methods",
"python"
] | stackoverflow_0074455225_magic_methods_methods_python.txt |
Q:
str.slice command in pandas unable to select desired part of string
I have the following dataframe in pandas:
d = {'Student Name': ['Omar 17BE004', '17BE005 Hussain', '17BE006 Anwar Syed']}
df_test = pd.DataFrame(data=d)
df_test.head(3)
I am trying to create a new column called Student_ID which will consist of th... | str.slice command in pandas unable to select desired part of string | I have the following dataframe in pandas:
d = {'Student Name': ['Omar 17BE004', '17BE005 Hussain', '17BE006 Anwar Syed']}
df_test = pd.DataFrame(data=d)
df_test.head(3)
I am trying to create a new column called Student_ID which will consist of the part of the string in the Student Name column representing student ID ... | [
"Use str.extract() for this\nd = {'Student Name': ['Omar 17BE004', '17BE005 Hussain', '17BE006 Anwar Syed']}\ndf_test = pd.DataFrame(data=d)\ndf_test['Student ID'] = df_test['Student Name'].str.extract(r'(\\b1\\w{6})')\nprint(df_test)\n\n Student Name Student ID\n0 Omar 17BE004 17BE004\n1 17BE... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"string"
] | stackoverflow_0074455741_dataframe_pandas_python_string.txt |
Q:
python pafy youtube to mp3 error, KeyError: 'dislike_count'
this is my code it is very simple:
import pafy
link = input("paste youtube link: ")
video = pafy.new(link)
bestaudio = video.getbestaudio()
print(video.title)
bestaudio.download()
and this is the error:
Traceback (most recent call last): File "c:\Us... | python pafy youtube to mp3 error, KeyError: 'dislike_count' | this is my code it is very simple:
import pafy
link = input("paste youtube link: ")
video = pafy.new(link)
bestaudio = video.getbestaudio()
print(video.title)
bestaudio.download()
and this is the error:
Traceback (most recent call last): File "c:\Users\neodi\Desktop\yt
to mp3\input.py", line 4, in
video = pafy.n... | [
"Temporary fix:\n\nrun pip install -e git+git://github.com/mohamed-challal/pafy.git@develop#egg=pafy\nor simply add -e git+git://github.com/mohamed-challal/pafy.git@develop#egg=pafy to your requirements.txt\n\n",
"I commented the backend_youtube_dl.py file\nline 53 and 54.\n"
] | [
0,
0
] | [] | [] | [
"pafy",
"python",
"visual_studio_code"
] | stackoverflow_0073519353_pafy_python_visual_studio_code.txt |
Q:
Groupby count() not working with datetime field
Im working with dataframes. I was trying to group the total count of records for each date. Data types of the 2 columns used are:
date (datetime64)
total_count (int64)
date total_count
2023-01-27 1
2023-01-27 3
2023-01-27 1
2023-01-27 8
... | Groupby count() not working with datetime field | Im working with dataframes. I was trying to group the total count of records for each date. Data types of the 2 columns used are:
date (datetime64)
total_count (int64)
date total_count
2023-01-27 1
2023-01-27 3
2023-01-27 1
2023-01-27 8
2023-01-27 1
From above, you can see for the ab... | [
"use sum() instead of count()\ndf.groupby('date')['total_count'].sum()\n"
] | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074455860_pandas_python.txt |
Q:
Conversion from String to Integer is not working while using MRJob
I'm writing a simple program which uses the mrjob library to map and reduce rows from a csv file.
One of the columns from a row is a yearID. This column is by default read in as a Str. I need to convert it to an Int so that I can compare it. For so... | Conversion from String to Integer is not working while using MRJob | I'm writing a simple program which uses the mrjob library to map and reduce rows from a csv file.
One of the columns from a row is a yearID. This column is by default read in as a Str. I need to convert it to an Int so that I can compare it. For some reason, the Str to Int conversion is not working and has weird behavi... | [
"I forgot to consider that the CSV header was being included in the mapped data. Oops!\nAfter adding a check to skip the header, the conversion works as expected.\n"
] | [
0
] | [] | [] | [
"mrjob",
"python",
"python_3.x",
"type_conversion"
] | stackoverflow_0074455644_mrjob_python_python_3.x_type_conversion.txt |
Q:
Permission Denied To Write To My Temporary File
I am attempting to create and write to a temporary file on Windows OS using Python. I have used the Python module tempfile to create a temporary file.
But when I go to write that temporary file I get an error Permission Denied. Am I not allowed to write to temporary ... | Permission Denied To Write To My Temporary File | I am attempting to create and write to a temporary file on Windows OS using Python. I have used the Python module tempfile to create a temporary file.
But when I go to write that temporary file I get an error Permission Denied. Am I not allowed to write to temporary files?! Am I doing something wrong? If I want to crea... | [
"NamedTemporaryFile actually creates and opens the file for you, there's no need for you to open it again for writing.\nIn fact, the Python docs state:\n\nWhether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it... | [
68,
30,
8,
4,
0,
0
] | [
"Permission was denied because the file is Open during line 2 of your code.\nclose it with f.close() first then you can start writing on your tempfile\n"
] | [
-4
] | [
"python",
"temporary_files"
] | stackoverflow_0023212435_python_temporary_files.txt |
Q:
convert to pydantic model from tuple
I want to map a tuple(list) to a pydantic model.
Is there a best practice to map tuple indexes to attributes in the following cases?
cryptwatch
from pydantic import BaseModel
class Ohlc(BaseModel):
close_time: float
open_time: float
high_price: float
low_pric... | convert to pydantic model from tuple | I want to map a tuple(list) to a pydantic model.
Is there a best practice to map tuple indexes to attributes in the following cases?
cryptwatch
from pydantic import BaseModel
class Ohlc(BaseModel):
close_time: float
open_time: float
high_price: float
low_price: float
close_price: float
volume... | [
"Assuming that data's length is always equal to the number of fields in your model, you can use __fields__ to achieve that.\nOhlc(**{key: data[i] for i, key in enumerate(Ohlc.__fields__.keys())})\n\n(There used to be fields which required you to use construct() first but now it is deprecated and now they tell you t... | [
3,
1,
0
] | [] | [] | [
"pydantic",
"python"
] | stackoverflow_0064026038_pydantic_python.txt |
Q:
regex - do not collect if formatted numbers before speific word anywhere in text string
I do not want to match the regex if any formatted number, such as $1,000 appears anywhere before a specific word in the text string.
In this case the word to find is "expungement" - but only if there is NO formatted value befor... | regex - do not collect if formatted numbers before speific word anywhere in text string | I do not want to match the regex if any formatted number, such as $1,000 appears anywhere before a specific word in the text string.
In this case the word to find is "expungement" - but only if there is NO formatted value before it.
So I would not want to match this string.
this is some initial text $11,000 recommends ... | [
"A pattern you can use is:\n^[^\\$]*(?!\\$[0-9,]+)expungement\n\nTo explain:\n\n^ is start of string\n[^$]* means match any character that is not '$', 0 or more times\n(?!x) means negative lookup for x. If x is found in the line, the match is negated\n\\$[0-9,]+ is a literal dollar sign followed by any combination ... | [
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074455869_python_regex.txt |
Q:
pandas dataframe: how to select rows where one column-value is like 'values in a list'
I have a requirement where I need to select rows from a dataframe where one column-value is like values in a list.
The requirement is for a large dataframe with millions of rows and need to search for rows where column-value is ... | pandas dataframe: how to select rows where one column-value is like 'values in a list' | I have a requirement where I need to select rows from a dataframe where one column-value is like values in a list.
The requirement is for a large dataframe with millions of rows and need to search for rows where column-value is like values of a list of thousands of values.
Below is a sample data.
NAME,AGE
Amar,80
Rames... | [
"You can pass all names in joined list by | for regex or, loop is not necessary:\ndf_res = df[df['NAME'].str.contains('|'.join(names_like), na=False)]\n\n",
"Use this hope you will find a great way.\ndf_res = df[df['NAME'].str.contains('|'.join(names_like), na=False)]\n"
] | [
1,
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074455909_dataframe_pandas_python_python_3.x.txt |
Q:
ModuleNotFoundError: No module named 'github'
trying to import github (PyGithub) but it keeps giving the same error, even though the lib is fully installed.
Code:
from github import Github
Output:
Traceback (most recent call last):
File "...path", line 1, in <module>
from github import Github
ModuleNotFound... | ModuleNotFoundError: No module named 'github' | trying to import github (PyGithub) but it keeps giving the same error, even though the lib is fully installed.
Code:
from github import Github
Output:
Traceback (most recent call last):
File "...path", line 1, in <module>
from github import Github
ModuleNotFoundError: No module named 'github'
Anyone know how to... | [
"This will install the package.\npip3 install PyGithub\n\nIf you're getting the same error that could be due to circular imports. Rename if you have any .py files named \"github.py\" in your work folder.\n"
] | [
0
] | [] | [] | [
"github",
"pygithub",
"python"
] | stackoverflow_0072652542_github_pygithub_python.txt |
Q:
Selenium unable to find DOM node index element on webpage
My goal is to scrape the src link within the video tag on this webpage. This is where I am seeing the video tag along with the link which I want.
I know how to grab the information within the tag using
driver.find_element(By.XPATH, '//video')
But when I ... | Selenium unable to find DOM node index element on webpage | My goal is to scrape the src link within the video tag on this webpage. This is where I am seeing the video tag along with the link which I want.
I know how to grab the information within the tag using
driver.find_element(By.XPATH, '//video')
But when I tried to find the Xpath of the tag by using the console, I was... | [
"You can get the source attribute with:\n[...]\nsource = driver.find_element(By.XPATH, '//video').get_attribute('src')\nprint(source)\n[...]\n\nResult in terminal:\nblob:https://mplayer.me/d420cb30-ed6e-4772-b169-ed33a5d3ee9f\n\nSee Selenium documentation at https://www.selenium.dev/documentation/\n"
] | [
1
] | [] | [] | [
"dom",
"html",
"javascript",
"python",
"web_scraping"
] | stackoverflow_0074455922_dom_html_javascript_python_web_scraping.txt |
Q:
Reshape two string columns to make count inbetween in Pandas
I have two columns and I want to reshape the table for a cross-count. How may I achieve this through Pandas?
data = {
"fruits": ["orange, apple, banana", "orange, apple, banana",
"apple, banana", "orange, apple, banana", "others"],
... | Reshape two string columns to make count inbetween in Pandas | I have two columns and I want to reshape the table for a cross-count. How may I achieve this through Pandas?
data = {
"fruits": ["orange, apple, banana", "orange, apple, banana",
"apple, banana", "orange, apple, banana", "others"],
"places": ["New York, London, Boston", "New York, Manchester",
... | [
"Let's procede by steps:\ndf2 = df.copy()\ndf2[\"fruits\"] = df[\"fruits\"].str.split(\", \")\ndf2[\"places\"] = df[\"places\"].str.split(\", \")\ndf2\n\n\ndf3 = df2.explode(\"fruits\").explode(\"places\")\ndf3.head()\n\n\npd.pivot_table(df3, index=\"fruits\", columns=\"places\", aggfunc=len, fill_value=0)\n# Or, u... | [
4,
3,
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0069462940_pandas_python.txt |
Q:
How to create new dataframe off of values from a previous dataframe?
I have a sample dataframe:
| ID | SampleColumn1| SampleColumn2 | SampleColumn3 | SampleColumn4 |
|:-- |:------------:| ------------ :| ------------ | ------------ |
| 1 |sample Apple | sample Cherry | sample Lime | sample Apple |
| 2 |sam... | How to create new dataframe off of values from a previous dataframe? | I have a sample dataframe:
| ID | SampleColumn1| SampleColumn2 | SampleColumn3 | SampleColumn4 |
|:-- |:------------:| ------------ :| ------------ | ------------ |
| 1 |sample Apple | sample Cherry | sample Lime | sample Apple |
| 2 |sample Cherry | sample lemon | sample Grape | sample Cherry |
I would like... | [
"You can do it using stack() and pivot_table()\nimport pandas as pd\ndf = pd.DataFrame([['Apple','Lime','Cherry','Apple'],['Cherry','Lemon','Grape','Cherry']])\ndf_stack = pd.DataFrame(df.stack()).droplevel(1).reset_index().rename(columns={0:'fruit'})\ndf_stack['values'] = 1\ndf_stack.pivot_table(index = 'index',co... | [
0,
0
] | [] | [] | [
"data_manipulation",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074454938_data_manipulation_dataframe_pandas_python.txt |
Q:
How to read the files of Azure file share as csv that is pandas dataframe
I have few csv files in my Azure File share which I am accessing as text by following the code:
from azure.storage.file import FileService
storageAccount='...'
accountKey='...'
file_service = FileService(account_name=storageAccount, accoun... | How to read the files of Azure file share as csv that is pandas dataframe | I have few csv files in my Azure File share which I am accessing as text by following the code:
from azure.storage.file import FileService
storageAccount='...'
accountKey='...'
file_service = FileService(account_name=storageAccount, account_key=accountKey)
share_name = '...'
directory_name = '...'
file_name = 'Name.... | [
"After reproducing from my end, I could able to read a csv file into dataframe from the contents of the file following the below code.\ngenerator = file_service.list_directories_and_files('fileshare/')\nfor file_or_dir in generator:\n print(file_or_dir.name)\n file=file_service.get_file_to_text('fileshare',''... | [
0
] | [] | [] | [
"azure",
"pandas",
"python"
] | stackoverflow_0074450247_azure_pandas_python.txt |
Q:
Merge words from a specific column into a row when other columns values are the same
I have dataframe
user
friend
food
mary
alex
fries
mary
eric
fries
How do I get the following dataframe
user
friend
food
mary
alex eric
fries
A:
I think you need join only unique values per user, then aggregate lambda funct... | Merge words from a specific column into a row when other columns values are the same | I have dataframe
user
friend
food
mary
alex
fries
mary
eric
fries
How do I get the following dataframe
user
friend
food
mary
alex eric
fries
| [
"I think you need join only unique values per user, then aggregate lambda function:\ndf = df.groupby('user', as_index=False).agg(lambda x: ' '.join(x.unique()))\n\n"
] | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074456034_dataframe_pandas_python.txt |
Q:
How can I convert CSV to JSON with data type in python or node.js?
I wanna convert CSV to JSON correct data type
csv file 2nd row is data type.
data has over 300 properties
example data:
Name
DMG
HP
Human
string
number
number
boolean
knight
100
500
true
archer
50
200
true
dog
-
-
-
if string empty return nul... | How can I convert CSV to JSON with data type in python or node.js? | I wanna convert CSV to JSON correct data type
csv file 2nd row is data type.
data has over 300 properties
example data:
Name
DMG
HP
Human
string
number
number
boolean
knight
100
500
true
archer
50
200
true
dog
-
-
-
if string empty return null
if number empty return 0
if boolean empty return false
my ... | [
"Options options..\nin this approach I cached the headerTypes and made a small helper function to return the intended type\ndefine the vars let i = 0, headerTypes = {};\nreplace your on.data code with this\n.on(\"data\", (data) => {\n if(i > 0){\n for(let prop in data){\n if(data.hasOwnProperty(... | [
1,
0
] | [] | [] | [
"csv",
"data_conversion",
"json",
"node.js",
"python"
] | stackoverflow_0074455652_csv_data_conversion_json_node.js_python.txt |
Q:
How to strip all whitespace from string
How do I strip all the spaces in a python string? For example, I want a string like strip my spaces to be turned into stripmyspaces, but I cannot seem to accomplish that with strip():
>>> 'strip my spaces'.strip()
'strip my spaces'
A:
Taking advantage of str.split's behavi... | How to strip all whitespace from string | How do I strip all the spaces in a python string? For example, I want a string like strip my spaces to be turned into stripmyspaces, but I cannot seem to accomplish that with strip():
>>> 'strip my spaces'.strip()
'strip my spaces'
| [
"Taking advantage of str.split's behavior with no sep parameter:\n>>> s = \" \\t foo \\n bar \"\n>>> \"\".join(s.split())\n'foobar'\n\nIf you just want to remove spaces instead of all whitespace:\n>>> s.replace(\" \", \"\")\n'\\tfoo\\nbar'\n\nPremature optimization\nEven though efficiency isn't the primary goal—wri... | [
387,
81,
40,
16,
16,
4,
3,
3,
3,
2,
1,
0,
0,
0
] | [] | [] | [
"python",
"python_3.x",
"spaces",
"strip"
] | stackoverflow_0003739909_python_python_3.x_spaces_strip.txt |
Q:
Can't import file in django
I am learning Django and I am trying to import the "views" file. this doesn't work-> "from . import views". It gives this error->ImportError: attempted relative import with no known parent package.
When I use "import views" it gives " Django.core.exceptions.ImproperlyConfigured: Request... | Can't import file in django | I am learning Django and I am trying to import the "views" file. this doesn't work-> "from . import views". It gives this error->ImportError: attempted relative import with no known parent package.
When I use "import views" it gives " Django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but se... | [
"where are you importing the file from? have you correctly configured your setting.py? what is your files structure?\nwe need more info to understand the problem\nEDIT: you could use\nfrom .views import about, anasayfa\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('about/', about, name='about')... | [
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0067038622_django_python.txt |
Q:
how to get the next word from a string according to list element in python
I am new to python and trying to solve this problem.
words = ['plus', 'Constantly', 'the']
string = "Plus, I Constantly adding new resources, guides, and the personality quizzes to help you travel beyond the Guidebook"
output: I adding G... | how to get the next word from a string according to list element in python | I am new to python and trying to solve this problem.
words = ['plus', 'Constantly', 'the']
string = "Plus, I Constantly adding new resources, guides, and the personality quizzes to help you travel beyond the Guidebook"
output: I adding Guidebook
here I want to match the list element to the string and get the next wo... | [
"One way to do this is to use regex to split string by words (the pattern used is [\\w]+). Then you can build a dictionary of the pairs, so that you can look up the first word to retrieve the following word.\nimport re\nwords = ['plus', 'Constantly', 'the'] \nstring = \"Plus, I Constantly adding new resources, gui... | [
1
] | [] | [] | [
"python",
"string"
] | stackoverflow_0074455896_python_string.txt |
Q:
(Python) TypeError: 'NoneType' object is not subscriptable , in function
I see lots of discusstion fixing 'NoneType error' such as this one Python - TypeError: 'NoneType' object is not subscriptable
but I read about 5 discussion , still don't know how to fix with my case
import numpy as np
import cv2
def show_im... | (Python) TypeError: 'NoneType' object is not subscriptable , in function | I see lots of discusstion fixing 'NoneType error' such as this one Python - TypeError: 'NoneType' object is not subscriptable
but I read about 5 discussion , still don't know how to fix with my case
import numpy as np
import cv2
def show_img(path):
img = cv2.imread(path)
b, g, r = img[:,:,0], img[:,:,1], img... | [
"File system paths can be sensitive to minor naming errors. In your case, there is an extra space at the end of the file name. At the shell level, this would have been stripped out, but the operating system API assumes you really did want that space there.\nFix, the space, but also consider adding error handling co... | [
1
] | [] | [] | [
"non_type",
"python",
"python_3.x"
] | stackoverflow_0074454579_non_type_python_python_3.x.txt |
Q:
Tried to upgrade pip, but error 'WinError 5' showed up
I've found a problem with pip and can't do anything with it anymore.
I'm on a Windows 7 computer and have a Dutch language (maybe it will occur problems with reading)
I did use pip version 8.1.1, but there's a newer version, 9.0.1. I installed it using 'pip in... | Tried to upgrade pip, but error 'WinError 5' showed up | I've found a problem with pip and can't do anything with it anymore.
I'm on a Windows 7 computer and have a Dutch language (maybe it will occur problems with reading)
I did use pip version 8.1.1, but there's a newer version, 9.0.1. I installed it using 'pip install --upgrade pip' and he's doing pretty well so it uninst... | [
"Not sure how many people will be drawn to this note, however, if you find yourself in the scenario where the pip install, terminal within PyCharm install, Python Package install, etc. methods are not working and you are receiving the errors that pygame is installed in Conda but module not recognized in PyCharm; it... | [
1,
0
] | [] | [] | [
"module",
"pip",
"python",
"windows"
] | stackoverflow_0041782175_module_pip_python_windows.txt |
Q:
How to open a text file which has more than 500k lines, without using any iteration?
I am working with text files and looping over them, python works well with files of 10k to 20k lines, most of them are of that length, few text files are over 100k lines, where the code just stops or just keeps buffering, how can ... | How to open a text file which has more than 500k lines, without using any iteration? | I am working with text files and looping over them, python works well with files of 10k to 20k lines, most of them are of that length, few text files are over 100k lines, where the code just stops or just keeps buffering, how can we improve the speed or open the text file directly, even if there has to be any iteration... | [] | [] | [
"I'm confused as to your \"without iteration\" parameter. You're already looping over the files and using a simple open or some other method, so what is it that you're wanting to change? As you didn't post your code at all there's nothing to work from to understand what might be happening or to suggest changes to.\... | [
-1
] | [
"memory",
"parsing",
"python",
"text",
"xml"
] | stackoverflow_0074455755_memory_parsing_python_text_xml.txt |
Q:
Is there a function to convert time HHMM (int64 in a df column) to a datetime object?
I am new to programming. Just started a few months ago and I hope I can get some help.
I have a flight delays dataset with columns 'Year', 'Month', 'DayOfMonth', 'DayOfWeek' and 'CRSDepTime' with int64 Dtype.
Screenshot of df
I n... | Is there a function to convert time HHMM (int64 in a df column) to a datetime object? | I am new to programming. Just started a few months ago and I hope I can get some help.
I have a flight delays dataset with columns 'Year', 'Month', 'DayOfMonth', 'DayOfWeek' and 'CRSDepTime' with int64 Dtype.
Screenshot of df
I need to perform analysis and visualistions to identify the month, day and time with the lowe... | [
"Use to_datetime with format by %H%M fr match HHMM and errors='coerce' for NaT if not parseable times, last use Series.dt.time:\ndf['CRSDepTime'] = pd.to_datetime(df['CRSDepTime'], format='%H%M', errors='coerce').dt.time\n\nFor vectorized solution for datetimes need to_datetime, only need Day column name and add co... | [
1,
0
] | [] | [] | [
"dataframe",
"datetime",
"pandas",
"python"
] | stackoverflow_0074456135_dataframe_datetime_pandas_python.txt |
Q:
How to get data from Azure file share using python
I have few csv files present in Azure file shares which I have to put it in pandas dataframe using python and do some operations.
The below code gets the data from containers:
dbutils.fs.mount(
source = "abfss://"+ container + "@" + storageAccountName + ".dfs.co... | How to get data from Azure file share using python | I have few csv files present in Azure file shares which I have to put it in pandas dataframe using python and do some operations.
The below code gets the data from containers:
dbutils.fs.mount(
source = "abfss://"+ container + "@" + storageAccountName + ".dfs.core.windows.net",
mount_point = "/mnt/" + container,
... | [
"As yurib Suggested to read data from Azure file share To databricks python we need to install Azure Storage File module.\n\nTo install Azure Storage File module, you need to use: pip install azure-storage-file\n\n\nAfter module is installed, you follow the below code to load the Azure Files to Azure Databricks.\n\... | [
0
] | [] | [] | [
"azure",
"azure_databricks",
"python"
] | stackoverflow_0074437319_azure_azure_databricks_python.txt |
Q:
finding rotated image coordinates
I'm using python and I have some images on my canvas that are rotated by different angles.
What I want to do is to get their coordinates while I know their previous position, axis and the angle they were rotated by.
It would also be enough if I can find coordinates of just one poi... | finding rotated image coordinates | I'm using python and I have some images on my canvas that are rotated by different angles.
What I want to do is to get their coordinates while I know their previous position, axis and the angle they were rotated by.
It would also be enough if I can find coordinates of just one point after rotation
| [
"To get a coordinate after it has been rotated, I would use numpy and a rotation matrix to derive its position:\n\nimport numpy as np\n\n# define parameters\npixel_column = 10\npixel_row = 20\ncenter_column = 50\ncenter_row = 50\n# angle goes counter-clockwise!\nrotation_angle_deg = 90\n\n\ndef get_rotation_matrix(... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074370956_python.txt |
Q:
django-cors-headers not working: No 'Access-Control-Allow-Origin' header is present on the requested resource
Full error:
Access to XMLHttpRequest at 'https://[redacted]/api/get_match_urls/' from origin 'https://trello.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control ... | django-cors-headers not working: No 'Access-Control-Allow-Origin' header is present on the requested resource | Full error:
Access to XMLHttpRequest at 'https://[redacted]/api/get_match_urls/' from origin 'https://trello.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I am making an API call from a... | [
"Could not make it work after trying everything mentioned here. In fact, everything mentioned in the django-cors-headers documentation was already there in my settings.py.\nAfter a lot of digging in, I found out the culprit was the \"MIDDLEWARE\" definition itself in settings.py. According to my version of django (... | [
2,
1
] | [] | [] | [
"cors",
"django",
"django_cors_headers",
"python"
] | stackoverflow_0068016687_cors_django_django_cors_headers_python.txt |
Q:
Fill data from database to Word (Django Python)
I don't know how to get data and fill into my word template. It's actually a long list, and I need to fill it on my table on word document. Am I doing it right? Here is my code:
views.py
def save_sample_details(request):
sample = SampleList.objects.all()
doc ... | Fill data from database to Word (Django Python) | I don't know how to get data and fill into my word template. It's actually a long list, and I need to fill it on my table on word document. Am I doing it right? Here is my code:
views.py
def save_sample_details(request):
sample = SampleList.objects.all()
doc = DocxTemplate("lab_management/word/sample_template.d... | [
"You're getting all SampleList objects when you call SampleList.objects.all() so this is returning a QuerySet of zero or more objects, rather than a single object - which is what you want.\nInstead you should get the single SampleList object you want: for example sample = SampleList.objects.get(id=1) or another ex... | [
2,
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074440338_django_python.txt |
Q:
python: extract variables values from `json` and use in `jupyter` notebook for a function throwing an error
I have a par.json file were i stored the variable values. And fetched the values in .py file successfully. I'm trying to run all function of .py file in jupyter notebook (all is in same location) where .py f... | python: extract variables values from `json` and use in `jupyter` notebook for a function throwing an error | I have a par.json file were i stored the variable values. And fetched the values in .py file successfully. I'm trying to run all function of .py file in jupyter notebook (all is in same location) where .py file already getting values from json file but while running in jupyter notebook it is throwing an error called as... | [
"Your imported module multi and its function h_b_acc() do not have access to your variables a_threshold and b_threshold. I recommend that you modify multi.h_b_acc() to pass them as optional arguments, so you can use the function in the Jupyer Notebook, as well as use your global variables in multi.py when needed. ... | [
0
] | [] | [] | [
"function",
"json",
"jupyter_notebook",
"python"
] | stackoverflow_0074456031_function_json_jupyter_notebook_python.txt |
Q:
Printing String after the user input on the same line
so basically i want to use the python input() function to get a velocity input from the user. After the user types the number i want to display a nit like m/s behind the user input.
I thought i can do something like this:
velocity = input("Please enter a veloci... | Printing String after the user input on the same line | so basically i want to use the python input() function to get a velocity input from the user. After the user types the number i want to display a nit like m/s behind the user input.
I thought i can do something like this:
velocity = input("Please enter a velocity: ", end='')
print("m/s")
but end='' only works with pri... | [
"You are already reading the user input into a variable called velocity. So you already have the value, you just need to print it and append m/s to it.\nHere's a way to do it -\nvelocity = input(\"Please enter a velocity: \")\nprint(velocity, end=\"m/s\\n\")\n\n\\n is newline character and is adding a newline after... | [
1
] | [
"The easiest way to do it is, to take the input in the print method.\ni.e\nprint(input(\"Please enter a velocity: \"), \"m/s\")\n\nOutPut\nPlease enter a velocity: 64\n64 m/s\n\n"
] | [
-1
] | [
"input",
"python"
] | stackoverflow_0074456013_input_python.txt |
Q:
opencv-python for Python 3.10, "Could not find a version that satisfies the requirement"
I am trying to install opencv with python using pip install opencv-python but I am getting this error
ERROR: Command errored out with exit status 1:
command: 'C:\Program Files\Python310\python.exe' 'C:\Users\gnara\AppData\L... | opencv-python for Python 3.10, "Could not find a version that satisfies the requirement" | I am trying to install opencv with python using pip install opencv-python but I am getting this error
ERROR: Command errored out with exit status 1:
command: 'C:\Program Files\Python310\python.exe' 'C:\Users\gnara\AppData\Local\Temp\pip-standalone-pip-_33ltocw\__env_pip__.zip\pip' install --ignore-installed --no-use... | [
"Looks like there is no opencv-python for Python 3.10... yet. Be patient.\nThis issue is being tracked already: https://github.com/opencv/opencv-python/issues?q=3.10\n",
"I have installed OpenCV with Python 3.10 on M1 using pip install opencv-python\nI hope it will work on Windows and Linux as well.\n",
"pip in... | [
3,
0,
0
] | [] | [] | [
"opencv",
"pip",
"python"
] | stackoverflow_0069480357_opencv_pip_python.txt |
Q:
Dropping rows from a CSV file in python
I trying to drop two rows from a CSV file and after exploring other similar questions I have not been able to figure it out still. I have tried using pandas and it does not seem to be working and I tried a few functions that people on here said worked for them but I could no... | Dropping rows from a CSV file in python | I trying to drop two rows from a CSV file and after exploring other similar questions I have not been able to figure it out still. I have tried using pandas and it does not seem to be working and I tried a few functions that people on here said worked for them but I could not get to work.
Here is my code I've ben tryin... | [
"df.drop does not modify the DataFrame inplace, unless you ask it to. It returns a new DataFrame. So, either\ndf = df.drop([9,20])\n\nor\ndf.drop([9,20],inplace=True)\n\n",
"df.drop(labels=[9, 21], axis=0, inplace=True)\n"
] | [
0,
0
] | [] | [] | [
"csv",
"pandas",
"python"
] | stackoverflow_0074456277_csv_pandas_python.txt |
Q:
Is there a way where i can remove trailing 1's at the end of a string as shown below
I have a list format as shown below.
stripped_list=['WLH1', 'GWJ1', 'AV11', 'UBN1']
I want to remove trailing 1's at the end but if i am using below code
stripped_list2 = [[item.replace('1', '') for item in z] for z in stripped_l... | Is there a way where i can remove trailing 1's at the end of a string as shown below | I have a list format as shown below.
stripped_list=['WLH1', 'GWJ1', 'AV11', 'UBN1']
I want to remove trailing 1's at the end but if i am using below code
stripped_list2 = [[item.replace('1', '') for item in z] for z in stripped_list]
it is stripping AV11 to AV only but i need AV1.
How to solve this?
I have a list for... | [
"Use re.sub with $ for match end of string for replace last 1:\nimport re\n\nstripped_list=['WLH1', 'GWJ1', 'AV11', 'UBN1']\n\nstripped_list2 = [re.sub( r'1$', '', z) for z in stripped_list]\n\nprint (stripped_list2)\n\n['WLH', 'GWJ', 'AV1', 'UBN']\n\nIf need remove all last values:\nstripped_list2 = [z[:-1] for z ... | [
1,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074456437_python.txt |
Q:
how to search a file name in pycharm?
How does one search for that file without manually looking in every directory and without making a script to do it?
when working on a large codebase one may have difficulty finding a file mentioned in a stack trace.
A:
Press Ctrl+Shift+N and select Files tab and type what yo... | how to search a file name in pycharm? | How does one search for that file without manually looking in every directory and without making a script to do it?
when working on a large codebase one may have difficulty finding a file mentioned in a stack trace.
| [
"Press Ctrl+Shift+N and select Files tab and type what you are looking for\nhttps://www.jetbrains.com/help/pycharm/part-1-finding-a-file-class-or-symbol-by-name.html#navigate-to-symbol\n"
] | [
1
] | [] | [] | [
"pycharm",
"python",
"windows"
] | stackoverflow_0074456478_pycharm_python_windows.txt |
Q:
Force type conversion in python dataclass __init__ method
I have the following very simple dataclass:
import dataclasses
@dataclasses.dataclass
class Test:
value: int
I create an instance of the class but instead of an integer I use a string:
>>> test = Test('1')
>>> type(test.value)
<class 'str'>
What I ac... | Force type conversion in python dataclass __init__ method | I have the following very simple dataclass:
import dataclasses
@dataclasses.dataclass
class Test:
value: int
I create an instance of the class but instead of an integer I use a string:
>>> test = Test('1')
>>> type(test.value)
<class 'str'>
What I actually want is a forced conversion to the datatype i defined in... | [
"The type hint of dataclass attributes is never obeyed in the sense that types are enforced or checked. Mostly static type checkers like mypy are expected to do this job, Python won't do it at runtime, as it never does.\nIf you want to add manual type checking code, do so in the __post_init__ method:\n@dataclasses.... | [
42,
17,
12,
3,
1,
0,
0,
0
] | [] | [] | [
"python",
"python_dataclasses"
] | stackoverflow_0054863458_python_python_dataclasses.txt |
Q:
How can I separate tuples into columns in a Pandas DataFrame?
I have these values in dataset in a pandas dataframe column
col1
[[1,2],[3,4],[5,6],[7,8],[9,10],[11,12]]
[[13,14],[15,16],[17,18],[19,20],[21,22],[23,24]]
I want to get 6 elements as list in new columns as rows.
This is the columns that I want to get.... | How can I separate tuples into columns in a Pandas DataFrame? | I have these values in dataset in a pandas dataframe column
col1
[[1,2],[3,4],[5,6],[7,8],[9,10],[11,12]]
[[13,14],[15,16],[17,18],[19,20],[21,22],[23,24]]
I want to get 6 elements as list in new columns as rows.
This is the columns that I want to get.
col2 col3
[1,3,5,7,9,11] [2,4,6,8,10,1... | [
"You can use a list comprehension and the DataFrame constructor:\ndf[['col2', 'col3']] = pd.DataFrame([list(map(list, zip(*l))) for l in df['col1']])\n\nAnother approach with numpy:\na = np.dstack(df['col1'].to_numpy())\ndf['col2'] = a[:,0].T.tolist()\ndf['col3'] = a[:,1].T.tolist()\n\nOutput:\n ... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074456386_dataframe_pandas_python.txt |
Q:
Get all post from users which my user follow
I would like to get all posts of all users which my user follow.
My User model looks like
from django.db import models
from django.contrib.auth.models import AbstractUser
from apps.friend_request.models import FriendRequest
# Save avatar to user specific directory in m... | Get all post from users which my user follow | I would like to get all posts of all users which my user follow.
My User model looks like
from django.db import models
from django.contrib.auth.models import AbstractUser
from apps.friend_request.models import FriendRequest
# Save avatar to user specific directory in media files
def user_avatar_directory(instance, fi... | [
"Your get_queryset should return a QuerySet, not a list. You furthermore do not need to obtain items with a loop, you can query with:\nfrom rest_framework.permissions import IsAuthenticated\n\nclass MyFollowersPosts(ListView):\n # …\n permission_classes = [IsAuthenticated]\n \n def get_queryset(self):\n... | [
0,
0
] | [] | [] | [
"django_models",
"django_rest_framework",
"django_views",
"python"
] | stackoverflow_0065564057_django_models_django_rest_framework_django_views_python.txt |
Q:
Why isn't ContentSettings cache_control max-age being honored in Azure storage blob via Python?
I can't seem to activate Cache-Control max-age in an Azure storage blob in Python via the following code:
contentSettings = ContentSettings(cache_control="max-age=86400")
containerClient.upload_blob(blobname, theByt... | Why isn't ContentSettings cache_control max-age being honored in Azure storage blob via Python? | I can't seem to activate Cache-Control max-age in an Azure storage blob in Python via the following code:
contentSettings = ContentSettings(cache_control="max-age=86400")
containerClient.upload_blob(blobname, theBytes, length=byteCount,
overwrite=True, content_settings=contentSettings)
In the web based Az... | [
"One possible reason for this could be the CORS settings which is preventing response headers being exposed to the client.\nPlease check the Exposed Headers CORS settings for blob service on the storage account and make sure all x-ms-* response headers are exposed.\nYou can also try by setting * (i.e. all response ... | [
0,
0
] | [] | [] | [
"azure",
"azure_blob_storage",
"azure_python_sdk",
"cache_control",
"python"
] | stackoverflow_0074453897_azure_azure_blob_storage_azure_python_sdk_cache_control_python.txt |
Q:
I need help converting an iterative function into a recursive function
Posting Homework is probably not that well recieved around here, but i'm seriously stuck.
My task, is to convert a String which contains a Tree in Newick-Format, into its bipartitions and I need to solve the problem recursivly.
E.g.:
tree = "((... | I need help converting an iterative function into a recursive function | Posting Homework is probably not that well recieved around here, but i'm seriously stuck.
My task, is to convert a String which contains a Tree in Newick-Format, into its bipartitions and I need to solve the problem recursivly.
E.g.:
tree = "((1,2),((3,((4,5),(6,7))),(8,9)))"
read_tree(tree)
Each branch of the tree a... | [
"In case it’s still useful.\nnewick=\"((1,2),((3,((4,5),(6,7))),(8,9)))\"\nbipart=list()\nleaf_set=set()\n\ndef getLeafs():\n for leaf in newick:\n if not leaf == \"(\" and not leaf == \")\" and not leaf == \",\":\n leaf_set.add(leaf)\n \ndef buildBiparts(index):\n if ... | [
0
] | [] | [] | [
"iteration",
"python",
"recursion"
] | stackoverflow_0074444876_iteration_python_recursion.txt |
Q:
'base_tags' is not a registered tag library. Must be one of:
Hello I get this error for create new custom template tags in django
how i can debug my code?
it's my template tags:
from django import template
from ..models import Category
register = template.Library()
@register.simple_tag
def title():
return "a... | 'base_tags' is not a registered tag library. Must be one of: | Hello I get this error for create new custom template tags in django
how i can debug my code?
it's my template tags:
from django import template
from ..models import Category
register = template.Library()
@register.simple_tag
def title():
return "any thing"
it's my HTML code:
{% load base_tags%}
<a ... | [
"You got this error because you have not added this tag in settings.py file\nchange this:\n@register.simple_tag\n\nTo this:\n@register.simple\n\nAnd in templates:\n{% load simple_tags %}\n\nAnd in settings.py file:\n'libraries':{\n 'simple_tags': 'templatetags.simple',\n }\n\nIf templateta... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074456262_django_python.txt |
Q:
How to plot a graph with logscale over a background image?
I want to plot a curve over a background image with the x and y axis in logscale. However, when I try to do so, the image is stretched by the logscale. I obtain this figure
This is the code I wrote.
import numpy as np
import matplotlib.pyplot as plt
x =... | How to plot a graph with logscale over a background image? | I want to plot a curve over a background image with the x and y axis in logscale. However, when I try to do so, the image is stretched by the logscale. I obtain this figure
This is the code I wrote.
import numpy as np
import matplotlib.pyplot as plt
x = np.random.uniform(low=0, high=10**6, size=(100,))
y = np.rando... | [
"Don't use twinx(), but create a new axes with matplotlib.pyplot.axes().\nYou can do like this controlling the frame(background), x/y axis, and z-order.\nfig, ax2 = plt.subplots()\nax2.plot(x, y) \nax2.set_xscale('log')\nax2.set_yscale('log')\nax2.set_frame_on(False)\nax2.zorder = 1\n\nax1 = plt.axes(ax2.get_positi... | [
0
] | [] | [] | [
"background_image",
"matplotlib",
"plot",
"python",
"scale"
] | stackoverflow_0074453652_background_image_matplotlib_plot_python_scale.txt |
Q:
AttributeError: type object 'DatasetV2' has no attribute 'save'
test_ds.save(path)
I want to save the tf.data.Dataset,but get the message "AttributeError: type object 'DatasetV2' has no attribute 'save'"
A:
using test_ds.save(path) I got new problem,"AttributeError: 'TensorSliceDataset' object has no attribute ... | AttributeError: type object 'DatasetV2' has no attribute 'save' | test_ds.save(path)
I want to save the tf.data.Dataset,but get the message "AttributeError: type object 'DatasetV2' has no attribute 'save'"
| [
"using test_ds.save(path) I got new problem,\"AttributeError: 'TensorSliceDataset' object has no attribute 'save'\"\n",
"refer to this answer: How to Save a Tensorflow Dataset\nfound out tf version is 2.8.0 in the runtime environment,using tf.data.experimental.save works.\n"
] | [
0,
0
] | [] | [] | [
"python",
"tensorflow2"
] | stackoverflow_0074456127_python_tensorflow2.txt |
Q:
tagging the column based on conditions
Existing Dataframe :
Id Month Year processed success
A Jan 2021 0 0
A Feb 2021 0 1
A Mar 2021 1 0
B Jan 2021 ... | tagging the column based on conditions | Existing Dataframe :
Id Month Year processed success
A Jan 2021 0 0
A Feb 2021 0 1
A Mar 2021 1 0
B Jan 2021 0 1
B Feb 2021 ... | [
"First create helper Series for test if not 1 in both columns by DataFrame.ne and DataFrame.all and then aggregate by GroupBy.agg with numpy.where:\ndf1 = (df[['processed','success']].ne(1).all(axis=1)\n .groupby(df['Id']).agg(lambda x: np.where(x[-3:].all(), 'UnPaid', 'Paid'))\n .reset_index(name='fi... | [
1,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074456583_dataframe_pandas_python.txt |
Q:
Is a cloned Conda environment Similar to a Python virtual environment
Is a cloned conda environment similar to a Python Virtual Environment?
conda create --clone arcgispro-py3 --name arcgispro-py3_clone
Or are there any benefits to create a Visual Environment for this cloned environment?
A:
I think I understan... | Is a cloned Conda environment Similar to a Python virtual environment | Is a cloned conda environment similar to a Python Virtual Environment?
conda create --clone arcgispro-py3 --name arcgispro-py3_clone
Or are there any benefits to create a Visual Environment for this cloned environment?
| [
"I think I understand what you're asking. \"virtual environment\" when it comes to python usually refers to python environments created using virtualenv specifically. You could consider conda environments \"virtual environments\" as well, but that just gets confusing to refer to them that way and people don't do ... | [
2
] | [] | [] | [
"anaconda",
"conda",
"python"
] | stackoverflow_0074455656_anaconda_conda_python.txt |
Q:
SQL query format
I have a list of string that I need to pass to an sql query.
listofinput = []
for i in input:
listofinput.append(i)
if(len(listofinput)>1):
listofinput = format(tuple(listofinput))
sql_query = f"""SELECT * FROM countries
w... | SQL query format | I have a list of string that I need to pass to an sql query.
listofinput = []
for i in input:
listofinput.append(i)
if(len(listofinput)>1):
listofinput = format(tuple(listofinput))
sql_query = f"""SELECT * FROM countries
where
... | [
"Change if(len(listofinput)>1): to if(len(listofinput)>=1):\nThis might work.\n",
"Remove condition if(len(listofinput)>1) .\nBecause if you don't convert to tuple your query should be like this:\n... where name in ['USA']\n\nor\n... where name in []\n\nand in [...] not acceptable in SQL, only in (...) is accepta... | [
0,
0,
0,
0
] | [] | [] | [
"database",
"database_performance",
"python",
"sql",
"tuples"
] | stackoverflow_0074456469_database_database_performance_python_sql_tuples.txt |
Q:
Extracting the Cloudant chat json multiple listed logs using pandas?
How to read the multiple listed JSON using pandas, we are connecting the Cloudant database and using the date filter to select the period. below is a code snippet. The expected outcome is to extract the JSON parameters into each column.
# Dat... | Extracting the Cloudant chat json multiple listed logs using pandas? | How to read the multiple listed JSON using pandas, we are connecting the Cloudant database and using the date filter to select the period. below is a code snippet. The expected outcome is to extract the JSON parameters into each column.
# Date filter
log_from_date = datetime.datetime.strptime('202210250000.... | [
"you can try something like this:\nfinal=pd.DataFrame()\nfor language in lang:\n client = Cloudant(cloudant_db_credential['serviceUsername'], cloudant_db_credential['servicePassword'], url=cloudant_db_credential['serviceURL'])\n client.connect()\n # Create an instance of the database.\n \n db = clien... | [
0
] | [] | [] | [
"dataframe",
"json",
"pandas",
"python"
] | stackoverflow_0074456029_dataframe_json_pandas_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.