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:
Replace all newline characters using python
I am trying to read a pdf using python and the content has many newline (crlf) characters. I tried removing them using below code:
from tika import parser
filename = 'myfile.pdf'
raw = parser.from_file(filename)
content = raw['content']
content = content.replace("\r\n",... | Replace all newline characters using python | I am trying to read a pdf using python and the content has many newline (crlf) characters. I tried removing them using below code:
from tika import parser
filename = 'myfile.pdf'
raw = parser.from_file(filename)
content = raw['content']
content = content.replace("\r\n", "")
print(content)
But the output remains uncha... | [
"content = content.replace(\"\\\\r\\\\n\", \"\")\n\nYou need to double escape them.\n",
"I don't have access to your pdf file, so I processed one on my system. I also don't know if you need to remove all new lines or just double new lines. The code below remove double new lines, which makes the output more read... | [
9,
2,
2,
1,
0,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0054760850_python_python_3.x.txt |
Q:
How to use a LDR to control and fan and LED ring and a timer
I have a LDR, 5v fan and a ws2812 LED ring. When the LDR sees light I want the fan to turn off and the LED to turn on. When the LDR doesn't see light I want the LED to turn off and the fan to turn on for 5 mins and then if the LDR doesn't see light for a... | How to use a LDR to control and fan and LED ring and a timer | I have a LDR, 5v fan and a ws2812 LED ring. When the LDR sees light I want the fan to turn off and the LED to turn on. When the LDR doesn't see light I want the LED to turn off and the fan to turn on for 5 mins and then if the LDR doesn't see light for a day I want the fan to turn on for 5 mins. For testing purposes I ... | [
"After you turn your LEDs on, create a timer that will shut them off after the configured amount of time.\nfrom machine import Timer\nTIMEOUT = 60 # expressed in seconds\nauto_off = Timer(0)\nauto_off.init(period=TIMEOUT*1000, mode=Timer.ONE_SHOT, callback=setOff)\n\n"
] | [
0
] | [] | [] | [
"micropython",
"multithreading",
"python",
"timer"
] | stackoverflow_0074353231_micropython_multithreading_python_timer.txt |
Q:
constant pandas warning in pycharm console "FutureWarning: iteritems is deprecated
Why does this code give me a warning message?
import pandas as pd
import numpy as np
test = pd.DataFrame({'a':np.array([0,1,2]), 'b': np.array([3,4,5])})
It seems anything I do in pandas throws these long error messages, I'm not s... | constant pandas warning in pycharm console "FutureWarning: iteritems is deprecated | Why does this code give me a warning message?
import pandas as pd
import numpy as np
test = pd.DataFrame({'a':np.array([0,1,2]), 'b': np.array([3,4,5])})
It seems anything I do in pandas throws these long error messages, I'm not sure if this is a problem with pycharm or if I'm doing something wrong in pandas.
| [
"You can ignore the warning, it is a known bug and is being fixed.\n"
] | [
1
] | [] | [] | [
"pandas",
"pycharm",
"python"
] | stackoverflow_0074501292_pandas_pycharm_python.txt |
Q:
extracting x and y data from a "messy" txt file
I assume the question might be quite basic, but I had no idea how I should search for this specific issue:
I have a .txt file where over several lines, several x-y data points are present per line. x and y values that belong together are seperated by a comma, while t... | extracting x and y data from a "messy" txt file | I assume the question might be quite basic, but I had no idea how I should search for this specific issue:
I have a .txt file where over several lines, several x-y data points are present per line. x and y values that belong together are seperated by a comma, while the the different couples are seperated by space.
Here... | [
"fileInp = \"2,20 12,40 13,100 14,300 15,440 16,10 24,50 25,350 26,2322 27,3323 28,9999 29,2152 30,2622 31,50\"\n\nx = list()\ny = list()\n\nfor data in fileInp.split():\n x_y_data = data.split(\",\")\n x.append(x_y_data[0])\n y.append(x_y_data[1])\n \n\nprint(x)\nprint(y)\n\n"
] | [
0
] | [] | [] | [
"python",
"txt"
] | stackoverflow_0074501237_python_txt.txt |
Q:
nextcord Command isn't working when I use Global Variables in f-strings
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.author.id == (isohel): #the userID for the user isohel is saved in the variable "isohel"
if f"@{bot}" in message.content:... | nextcord Command isn't working when I use Global Variables in f-strings | @client.event
async def on_message(message):
if message.author == client.user:
return
if message.author.id == (isohel): #the userID for the user isohel is saved in the variable "isohel"
if f"@{bot}" in message.content: #the bots ID is saved in the variable bot.
await message.reply("... | [
"When I tried this code that you gave me it worked so I think there may be a problem elsewhere. This was the code that I used. Try changing the variables to match yours then test this code. I'm not sure if you are using nextcord or discord.py but this is how it would work in discord.py:\nimport random\nimport disco... | [
0
] | [] | [] | [
"discord",
"nextcord",
"python"
] | stackoverflow_0074501228_discord_nextcord_python.txt |
Q:
Failed building wheel for PyAudio (M1 chip)
When I try to install PyAudio on my MAC (M1) with the command:
pip install PyAudio
I get the following error:
Collecting PyAudio
Using cached PyAudio-0.2.12.tar.gz (42 kB)
Installing build dependencies ... done
Getting requirements to build wheel ... done
Prepar... | Failed building wheel for PyAudio (M1 chip) | When I try to install PyAudio on my MAC (M1) with the command:
pip install PyAudio
I get the following error:
Collecting PyAudio
Using cached PyAudio-0.2.12.tar.gz (42 kB)
Installing build dependencies ... done
Getting requirements to build wheel ... done
Preparing metadata (pyproject.toml) ... done
Building w... | [
"\n\ntry\nsudo apt update\nsudo apt install portaudio19-dev\npip install pyaudio\n\n\n\n"
] | [
0
] | [] | [] | [
"pip",
"pyaudio",
"python"
] | stackoverflow_0074394845_pip_pyaudio_python.txt |
Q:
Class (static) variables and methods
How do I create class (i.e. static) variables or methods in Python?
A:
Variables declared inside the class definition, but not inside a method are class or static variables:
>>> class MyClass:
... i = 3
...
>>> MyClass.i
3
As @millerdev points out, this creates a class-... | Class (static) variables and methods | How do I create class (i.e. static) variables or methods in Python?
| [
"Variables declared inside the class definition, but not inside a method are class or static variables:\n>>> class MyClass:\n... i = 3\n...\n>>> MyClass.i\n3 \n\nAs @millerdev points out, this creates a class-level i variable, but this is distinct from any instance-level i variable, so you could have\n>>> m = M... | [
2264,
745,
266,
45,
28,
24,
23,
17,
16,
14,
12,
11,
11,
10,
9,
9,
6,
6,
5,
4,
3,
3,
2,
1,
0,
0,
0
] | [] | [] | [
"class",
"class_variables",
"python",
"static"
] | stackoverflow_0000068645_class_class_variables_python_static.txt |
Q:
PYSimpleGui event in combination with keyboard.is_pressed('key') working every time, except first time after program start
PYSimpleGui event in combination with keyboard.is_pressed('key') working every time, except first time after program start. So the first click never works, but every other click works.
Hardcod... | PYSimpleGui event in combination with keyboard.is_pressed('key') working every time, except first time after program start | PYSimpleGui event in combination with keyboard.is_pressed('key') working every time, except first time after program start. So the first click never works, but every other click works.
Hardcoding my button event is not an option, I have to check for several keys, the program is pretty complex already. File explorer.
Tr... | [
"Ok I found the solution!!\nI just have to put ANY arbitrary keyboard read in, after the program starts.\nIt can be keyboard.get_hotkey_name() or keyboard.is_pressed('shift') or keyboard.is_pressed('a')\nFull solution:\nimport PySimpleGUI as sg\nimport keyboard\nfrom time import sleep\n\nkeyboard.get_hotkey_name() ... | [
0
] | [] | [] | [
"keyboard_events",
"pysimplegui",
"python"
] | stackoverflow_0074485353_keyboard_events_pysimplegui_python.txt |
Q:
Getting the image of an element in a website with Selenium
In this website there is a board at the center. If you click on it with the right mouse button, it is possible to copy/save its image. In this sense, I want to code with Selenium a way to get this image. However, the board's element is only given by
<canva... | Getting the image of an element in a website with Selenium | In this website there is a board at the center. If you click on it with the right mouse button, it is possible to copy/save its image. In this sense, I want to code with Selenium a way to get this image. However, the board's element is only given by
<canvas width="640" height="640" class="board-canvas"></canvas>
Which... | [
"Since it is a canvas, we can use the command HTMLCanvasElement.toDataURL().\nReturns the image as a base64-encoded string. You then simply decode it and write it to a file.\nThis is a complete example of reproducible code:\nfrom selenium import webdriver\nfrom webdriver_manager.chrome import ChromeDriverManager\nf... | [
1
] | [] | [] | [
"python",
"python_3.x",
"selenium"
] | stackoverflow_0074501154_python_python_3.x_selenium.txt |
Q:
Fill column based on conditional max value in Pandas
I have a dataframe that looks like this (link to csv):
id, time, value, approved
0, 0:00, 10, false
1, 0:01, 20, false
1, 0:02, 50, false
1, 0:03, 20, true
1, 0:04, 40, true
1, 0:05, 40, true
1, 0:06, 20, false
2, 0:07, 35, false
... | Fill column based on conditional max value in Pandas | I have a dataframe that looks like this (link to csv):
id, time, value, approved
0, 0:00, 10, false
1, 0:01, 20, false
1, 0:02, 50, false
1, 0:03, 20, true
1, 0:04, 40, true
1, 0:05, 40, true
1, 0:06, 20, false
2, 0:07, 35, false
2, 0:08, 35, false
2, 0:09, 50, true
2, 0:10, 50,... | [
"Here is an approach using pandas.DataFrame.mask based on your solution :\napproved_1st_max = df.mask(~df[\"approved\"]).groupby(\"id\")[\"value\"].transform('idxmax')\n\ndf[\"is_max\"]= df.reset_index()[\"index\"].eq(approved_1st_max)\n\n# Output :\nprint(df)\n\n id time value approved is_max\n0 0 0:00 ... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074501097_pandas_python.txt |
Q:
asyncio: Why does cancelling a task lead to cancellation of other tasks added into the event loop?
I use a coroutine to add another coroutine to the event loop multiple times but partway through I cancel the first coroutine. I thought this would mean that any coroutines already added to the event loop would comple... | asyncio: Why does cancelling a task lead to cancellation of other tasks added into the event loop? | I use a coroutine to add another coroutine to the event loop multiple times but partway through I cancel the first coroutine. I thought this would mean that any coroutines already added to the event loop would complete successfully and no more would be added, however I find that coroutines that have already been added ... | [
"That's because tour task is waiting on another task:\nasync def runTimes(async_func, times):\n for i in range(0, times):\n task = loop.create_task(async_func())\n await task ## HERE!\n\nAs per asyncio's documentation:\n\nTo cancel a running Task use the cancel() method. Calling it will\ncause the ... | [
0,
0
] | [] | [] | [
"python",
"python_asyncio"
] | stackoverflow_0074501298_python_python_asyncio.txt |
Q:
No module named 'bcolors' although 'Requirement already satisfied'
I am trying to use bcolors in my python code in Spyder/Anaconda but it keeps telling me
ModuleNotFoundError: No module named 'bcolors'.
So I installed it with pip install bcolorswhich gave me Requirement already satisfied: bcolors in e:\anaconda3\l... | No module named 'bcolors' although 'Requirement already satisfied' | I am trying to use bcolors in my python code in Spyder/Anaconda but it keeps telling me
ModuleNotFoundError: No module named 'bcolors'.
So I installed it with pip install bcolorswhich gave me Requirement already satisfied: bcolors in e:\anaconda3\lib\site-packages (1.0.4), but it still doesn't work.
What am I doing wro... | [
"You had that error because you are in different interpreter trying to import the module. You should append the path of the module to your working directory.\nimport sys\n\nsys.path.append(\"\\anaconda3\\lib\\site-packages\")\n\nimport bcolors\n\n",
"Have you tried installing the pandas' library using pip instal... | [
1,
0,
0
] | [] | [] | [
"anaconda",
"python"
] | stackoverflow_0073531265_anaconda_python.txt |
Q:
trouble understanding list.begin() | list.end() | list::iterator i
void Graph::max_path(){
for(int i=0; i <N; i++){
cost[i]=0; cam_max[i]=999;
}
// Percorre todos os vertices adjacentes do vertice
int max = 0;
list<int>::iterator i;
for (int a = 0; a < N ; a++){
int v = ordel... | trouble understanding list.begin() | list.end() | list::iterator i | void Graph::max_path(){
for(int i=0; i <N; i++){
cost[i]=0; cam_max[i]=999;
}
// Percorre todos os vertices adjacentes do vertice
int max = 0;
list<int>::iterator i;
for (int a = 0; a < N ; a++){
int v = ordely[a];
for (i = adj[v].begin(); i != adj[v].end(); ++i){
... | [
"begin and end are iterators (specfically, pointers), which are used to iterate over a container.\nYou could imagine begin as 0 and end as the size of an array. So it is like for (i = 0; i < size; ++i).\nHowever, the thing about pointers is that they're addresses, so in C++, i < end (where i started as begin) is mo... | [
0
] | [] | [] | [
"c++",
"code_conversion",
"python"
] | stackoverflow_0074501189_c++_code_conversion_python.txt |
Q:
Error "Microsoft Visual C++ 14.0 is required (Unable to find vcvarsall.bat)"
I've installed Python 3.5 and while running
pip install mysql-python
it gives me the following error
error: Microsoft Visual C++ 14.0 is required (Unable to find vcvarsall.bat)
I have added the following lines to my Path
C:\Program Fil... | Error "Microsoft Visual C++ 14.0 is required (Unable to find vcvarsall.bat)" | I've installed Python 3.5 and while running
pip install mysql-python
it gives me the following error
error: Microsoft Visual C++ 14.0 is required (Unable to find vcvarsall.bat)
I have added the following lines to my Path
C:\Program Files\Python 3.5\Scripts\;
C:\Program Files\Python 3.5\;
C:\Windows\System32;
C:\Pro... | [
"Your path only lists Visual Studio 11 and 12, it wants 14, which is Visual Studio 2015. If you install that, and remember to tick the box for Languages → C++ then it should work.\nOn my Python 3.5 install, the error message was a little more useful, and included the URL to get it from:\n\nerror: Microsoft Visual C... | [
185,
156,
114,
81,
61,
28,
20,
17,
14,
13,
12,
12,
11,
9,
6,
6,
5,
4,
3,
3,
3,
3,
2,
2,
2,
2,
2,
1,
1,
1,
1,
1,
0,
0,
0,
0
] | [] | [] | [
"python",
"python_3.x",
"visual_c++"
] | stackoverflow_0029846087_python_python_3.x_visual_c++.txt |
Q:
ModuleNotFoundError: No module named 'pyperclip'
Similar issues like this have been posted on StackOverflow but I did not find adequate answers to resolve this issue.
I'm running Python 3.6.3 on a Windows 7 machine. From IDLE I type the following import stmt and get the subsequent error:
>>> import pyperclip
Trac... | ModuleNotFoundError: No module named 'pyperclip' | Similar issues like this have been posted on StackOverflow but I did not find adequate answers to resolve this issue.
I'm running Python 3.6.3 on a Windows 7 machine. From IDLE I type the following import stmt and get the subsequent error:
>>> import pyperclip
Traceback (most recent call last):
File "<pyshell#5>", l... | [
"There is a problem with the current version of the pyperclip I checked the git repo and opened a pull request for the issue. It currently doesn't support use for python3.7\n",
"You must navigate to your default install location for 3.6. For IDLE 32 bits it's:\nC:\\Users\\<username>\\AppData\\Local\\Programs\\Pyt... | [
4,
3,
2,
1,
0,
0,
0,
0
] | [] | [] | [
"pyperclip",
"python"
] | stackoverflow_0047684616_pyperclip_python.txt |
Q:
Create DataFrame column with pairwise Last In First Out method as condition
I have a DataFrame df1 with following columns: Date, Direction, Input, Output, and Amount.
df1
Date Direction Input Output Amount
0 2022-01-02 In 18.5 0.0 1.0
1 2022-01-03 In 18.0 0.0 2... | Create DataFrame column with pairwise Last In First Out method as condition | I have a DataFrame df1 with following columns: Date, Direction, Input, Output, and Amount.
df1
Date Direction Input Output Amount
0 2022-01-02 In 18.5 0.0 1.0
1 2022-01-03 In 18.0 0.0 2.0
2 2022-01-04 Out 0.0 18.5 2.0
3 2022-01-05 In 16... | [
"The proper description for the problem should Last In First Out: the last unused In row is matched to each Out row.\nYou can solve this using a stack-based approach with deque:\nfrom collections import deque\n\ninputs = deque()\namount = []\n\nfor row in df1[[\"Direction\", \"Input\", \"Output\"]].itertuples():\n ... | [
2
] | [] | [] | [
"dataframe",
"numpy",
"pandas",
"python"
] | stackoverflow_0074501233_dataframe_numpy_pandas_python.txt |
Q:
Initialise a class with objects of another class
say I have a class which describes a ball and its properties:
class Ball:
def __init__(self, m=0.0,x=0.0, y=0.0):
self.m = m
self.x = x
self.y = y
self.r = np.array([x,y])
def pos(self):
print('Current positio... | Initialise a class with objects of another class | say I have a class which describes a ball and its properties:
class Ball:
def __init__(self, m=0.0,x=0.0, y=0.0):
self.m = m
self.x = x
self.y = y
self.r = np.array([x,y])
def pos(self):
print('Current position is:', self.r)
def move(self, x_mo... | [
"You are very close. You just need to pass the ball into the __init__() method and store it on the instance:\nclass Simulation:\n def __init___(self, ball, r):\n self.ball = ball\n ...\n\n def next_move(self):\n position_after_next_move = self.ball.pos()\n\na = Ball(2,2,2)\ns = Simulation... | [
2
] | [] | [] | [
"class",
"python"
] | stackoverflow_0074501406_class_python.txt |
Q:
Project created but its fields are empty when sent from React to Django API
I've been working on this React + Django APP. And I have been making a simple CRUD functionality into this app. everything goes fine but when i came to create project and send it to the django database, it gets created but when i look at i... | Project created but its fields are empty when sent from React to Django API | I've been working on this React + Django APP. And I have been making a simple CRUD functionality into this app. everything goes fine but when i came to create project and send it to the django database, it gets created but when i look at it at projects/list it only shows the delete button and and image field which is n... | [
"I tried a lot of solutions but nothing worked. It turns out the problem in in the CreateProject.js components where the createProject() is.\nso this is how i fixed it:\nAt first I was just sending the data fields like this:\ntitle: project.title,\nbody: project.body,\n\nbut I should have been:\nbody: JSON.stringif... | [
0
] | [] | [] | [
"django",
"javascript",
"python",
"reactjs",
"web_deployment"
] | stackoverflow_0074362233_django_javascript_python_reactjs_web_deployment.txt |
Q:
cv2.imshow() crashes on Mac
When I am running this piece of code on ipython (MacOS /python 2.7.13)
cv2.startWindowThread()
cv2.imshow('img', img)
cv2.waitKey()
cv2.destroyAllWindows()
the kernel crashes. When the image appears, the only button that I can press is minimise (the one in the middle and when I press ... | cv2.imshow() crashes on Mac | When I am running this piece of code on ipython (MacOS /python 2.7.13)
cv2.startWindowThread()
cv2.imshow('img', img)
cv2.waitKey()
cv2.destroyAllWindows()
the kernel crashes. When the image appears, the only button that I can press is minimise (the one in the middle and when I press any key then the spinning wheel s... | [
"Do you just want to look at the image? I'm not sure what you want to do with startWindowThread, but if you want to install opencv the easiest way, open the image, and view it try this:\ninstall conda (A better package manager for opencv than homebrew)\nthen create a cv environment:\nconda create -n cv\n\nactivate ... | [
6,
4,
3,
2,
0
] | [] | [] | [
"ipython",
"macos",
"opencv",
"python"
] | stackoverflow_0046348972_ipython_macos_opencv_python.txt |
Q:
Reindex and Interpolate data
Suppose I have the following data frame.
index = [0.018519, 0.037037, 0.055556, 0.074074, 0.092593, 0.111111, 0.12963, 0.148148, 0.166667, 0.185185,
0.203704, 0.222222, 0.240741, 0.259259, 0.277778, 0.296296, 0.314815, 0.333333, 0.351852, 0.37037... | Reindex and Interpolate data | Suppose I have the following data frame.
index = [0.018519, 0.037037, 0.055556, 0.074074, 0.092593, 0.111111, 0.12963, 0.148148, 0.166667, 0.185185,
0.203704, 0.222222, 0.240741, 0.259259, 0.277778, 0.296296, 0.314815, 0.333333, 0.351852, 0.37037,
0.388889, 0.407407, 0.42... | [
"Here is one way to do it:\n# Add new values\ndf = pd.concat(\n [df, pd.DataFrame(data=[pd.NA for _ in range(len(new_index))], index=new_index)]\n)\n\n# Remove duplicated indices, sort, interpolate and get rid of values not in new_index\ndf = (\n df.loc[~df.index.duplicated(keep=\"first\"), :]\n .sort_inde... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074485697_pandas_python.txt |
Q:
How to display data from a dictionary within a list in a readable format?
The data needs to be stored in this format
data = {'admin': [{'title': 'Register Users with taskManager.py', 'description': 'Use taskManager.py to add the usernames and passwords for all team members that will be using this program.', 'due d... | How to display data from a dictionary within a list in a readable format? | The data needs to be stored in this format
data = {'admin': [{'title': 'Register Users with taskManager.py', 'description': 'Use taskManager.py to add the usernames and passwords for all team members that will be using this program.', 'due date': '10 Oct 2019', 'date assigned': '20 Oct 2019', 'status': 'No'}, {'title':... | [] | [] | [
"Try this:\ndict = #your dict here\nfor user in dict.values():\n print(f\"user: {user}\")\n for k, v in dict[user]: # selects sub dicts\n print (f\"{k}: {v})\n\n",
"You basically have a densely nested structure so if this is the final structure of your data then the easiest way is unravel it in a hard coded ... | [
-1,
-1,
-1
] | [
"dictionary",
"list",
"python"
] | stackoverflow_0074501637_dictionary_list_python.txt |
Q:
PM2.js to Run Gunicorn/Flask App inside Virtualenv/Anaconda env
I have been running gunicorn to serve a Python Flask app using the commands
conda activate fooenv
gunicorn --workers=4 -b 0.0.0.0:5000 --worker-class=meinheld.gmeinheld.MeinheldWorker api.app:app
How can we use pm2 instead to run gunicorn/flask app ... | PM2.js to Run Gunicorn/Flask App inside Virtualenv/Anaconda env | I have been running gunicorn to serve a Python Flask app using the commands
conda activate fooenv
gunicorn --workers=4 -b 0.0.0.0:5000 --worker-class=meinheld.gmeinheld.MeinheldWorker api.app:app
How can we use pm2 instead to run gunicorn/flask app inside the fooenv environment?
| [
"supposed you can run gunicorn in your venv via e.g.:\ngunicorn wsgi:app -b localhost:5010\n\nthen you simply use command (in the venv):\npm2 --name=myapp start \"gunicorn wsgi:app -b localhost:5010\"\n\n(took me way too long to figure this out btw)\n",
"I would create a pm2.json file in the same directory as you... | [
2,
1,
0
] | [] | [] | [
"conda",
"flask",
"gunicorn",
"pm2",
"python"
] | stackoverflow_0066272697_conda_flask_gunicorn_pm2_python.txt |
Q:
Networkx KeyError: 'source' with from_pandas_edgelist for undirected edgelist
I have an edgelist in a pandas dataframe that looks like this:
topic neighbor
0 K Kl
1 K Pr
2 Kl TS
3 Pr Kl
4 Pr Pr
When I turn this into a Graph (using networkx as nx) with G = nx.from_pandas_... | Networkx KeyError: 'source' with from_pandas_edgelist for undirected edgelist | I have an edgelist in a pandas dataframe that looks like this:
topic neighbor
0 K Kl
1 K Pr
2 Kl TS
3 Pr Kl
4 Pr Pr
When I turn this into a Graph (using networkx as nx) with G = nx.from_pandas_edgelist(df) it gives me KeyError: 'source'.
It works when I specify a source and t... | [
"Try this:\nimport pandas as pd\nimport networkx as nx\n\ndf = pd.read_clipboard()\nprint(df)\n\nOutput:\n topic neighbor\n0 K Kl\n1 K Pr\n2 Kl TS\n3 Pr Kl\n4 Pr Pr\n\nUse source and target parameters:\nG = nx.from_pandas_edgelist(df, source='topic', target='neighbor'... | [
2,
1
] | [] | [] | [
"networkx",
"pandas",
"python"
] | stackoverflow_0074501737_networkx_pandas_python.txt |
Q:
How to fetch two table's information from a same webpage?
I have to go to here
Here I have to choose applicant name = “ASIAN PAINTS” (as an example)
By this code, [Google Colab]
!pip install selenium
!apt-get update
!apt install chromium-chromedriver
import re
import csv
import json
from time import sleep
from ... | How to fetch two table's information from a same webpage? | I have to go to here
Here I have to choose applicant name = “ASIAN PAINTS” (as an example)
By this code, [Google Colab]
!pip install selenium
!apt-get update
!apt install chromium-chromedriver
import re
import csv
import json
from time import sleep
from typing import Generator, List, Tuple
from selenium import webdr... | [
"First-Step - GET the 2nd table CSS-Selector (after Code-Line 121):\n...\ntable_values_locator = (By.CSS_SELECTOR, 'input+.tab-pane tr:not(:first-child)>td:last-child')\n# read 2nd Table\ntable2_values_locator = (By.CSS_SELECTOR, 'table tr:nth-of-type(2)')\n....\n\nSecond-Step - add the data form 2nd table css-sele... | [
0
] | [] | [] | [
"python",
"selenium_chromedriver",
"web_scraping"
] | stackoverflow_0074423654_python_selenium_chromedriver_web_scraping.txt |
Q:
how to modify certain phrases in a string in python
WHAT I AM TRYING TO DO:
i am trying to add certian acronyms to any random string that is entered by the user, for example like:
input (by the user):
'by the way i called them and they were not having any of it laugh out loud!'
output(by the program):
'btw i calle... | how to modify certain phrases in a string in python | WHAT I AM TRYING TO DO:
i am trying to add certian acronyms to any random string that is entered by the user, for example like:
input (by the user):
'by the way i called them and they were not having any of it laugh out loud!'
output(by the program):
'btw i called them and they were not having any of it lol!
WHAT I TRI... | [
"If you have a list of abbreviations then you can just loop through every abbreviation and replace all instances in a string:\nabbr = {\n \"by the way\": \"btw\",\n \"laugh out loud\": \"lol\"\n}\nstring = \"by the way I called them and they were not having any of it laugh out loud!\"\nfor full, short in abbr... | [
1
] | [] | [] | [
"list",
"python",
"string"
] | stackoverflow_0074501778_list_python_string.txt |
Q:
Django - issue with Not Null constraint
Hi in my program I keep receiving the above exception and am unsure why. The issue happens when my requestLessons_view method tries to save the form.
Views.py
def requestLessons_view(request):
if request.method == 'POST':
form = RequestLessonsForm(request.POST)
... | Django - issue with Not Null constraint | Hi in my program I keep receiving the above exception and am unsure why. The issue happens when my requestLessons_view method tries to save the form.
Views.py
def requestLessons_view(request):
if request.method == 'POST':
form = RequestLessonsForm(request.POST)
if form.is_valid() & request.user.is_... | [
"Your .save() method is defined on the Meta class, not the form, hence the error. I would advise to let the model form handle the logic: a ModelForm can be used both to create and update the items, so by doing the save logic yourself, you basically make the form less effective. You can rewrite this to:\nclass Reque... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074501789_django_python.txt |
Q:
Fbprophet installation error - failed building wheel for fbprophet
I am trying to install fbprophet for Python using Pip install, but failing. I have already installed Pystan.
Can I import it using Anaconda Navigator?
Can someone please help.
Failed building wheel for fbprophet
Running setup.py clean for fbprophet... | Fbprophet installation error - failed building wheel for fbprophet | I am trying to install fbprophet for Python using Pip install, but failing. I have already installed Pystan.
Can I import it using Anaconda Navigator?
Can someone please help.
Failed building wheel for fbprophet
Running setup.py clean for fbprophet
Failed to build fbprophet
Installing collected packages: fbprophet
Ru... | [
"Fundamental step:\nSwitch to your environment in your Anaconda prompt: \nconda activate name-of-your-python-enviornment\nThen the following steps shall work:\n\nOn Prompt install Ephem:\nconda install -c anaconda ephem\n\nInstall Pystan:\nconda install -c conda-forge pystan\n\nFinally install Fbprophet:\nconda ins... | [
20,
5,
3,
2,
1,
1,
0,
0,
0,
0
] | [
"After a lot of research, I found the solution for installing fbprophet on windows 10.\nStep 1: Check the kernel in jupyter.\nLocate the folder \\jupyter\\kernels\\python3 and check the python exe location used by the kernel.\nMine was pointing to - Programs\\Python\\Python37\\python.exe\nopen CMD prompt and go to ... | [
-1,
-1,
-1
] | [
"anaconda",
"facebook_prophet",
"python",
"python_3.x"
] | stackoverflow_0049889404_anaconda_facebook_prophet_python_python_3.x.txt |
Q:
File Names Chain in python
I CANNOT USE ANY IMPORTED LIBRARY. I have this task where I have some directories containing some files; every file contains, besides some words, the name of the next file to be opened, in its first line. Once every word of every files contained in a directory is opened, they have to be ... | File Names Chain in python | I CANNOT USE ANY IMPORTED LIBRARY. I have this task where I have some directories containing some files; every file contains, besides some words, the name of the next file to be opened, in its first line. Once every word of every files contained in a directory is opened, they have to be treated in a way that should ret... | [
"This assignment is relatively easy, if the code has a good structure. Here is a full implementation:\ndef read_file(fname):\n with open(fname, 'r') as f:\n return list(filter(None, [y.rstrip(' \\n').lstrip(' ') for x in f for y in x.split()]))\n\ndef read_chain(fname):\n seen = set()\n new = ... | [
2,
1
] | [] | [] | [
"file",
"list",
"python",
"slice",
"string"
] | stackoverflow_0074500987_file_list_python_slice_string.txt |
Q:
How do I further melt horizontal values into vertical values?
I have a dataframe which has horizontal identifiers (yes and no) and values, and I want to melt it into vertical values into each yes. Here is a snippet of my dataframe:
option Region Store Name option1 option2 optio... | How do I further melt horizontal values into vertical values? | I have a dataframe which has horizontal identifiers (yes and no) and values, and I want to melt it into vertical values into each yes. Here is a snippet of my dataframe:
option Region Store Name option1 option2 option3 option4 profit
0 Region 1 ... | [
"IIUC, does this work?\ndf.melt(['option', 'Region', 'Store Name', 'profit'], var_name='options')\\\n .query(\"value == 'Y'\")\\\n .drop('value', axis=1)\\\n .sort_values('profit')\n\nOutput:\n option Region Store Name profit options\n0 0 Region1 Store 1 48.1575 option1\n6 0 Region... | [
1
] | [] | [] | [
"pandas",
"pandas_melt",
"python"
] | stackoverflow_0074501347_pandas_pandas_melt_python.txt |
Q:
How do i set row height in a table?
I'm using the python library borb to create a PDF document.
I want to set the row height in a table. If i use
TableCell(paragraph, preferred_width=Decimal(150), preferred_height=Decimal(200))
in a FlexibleColumnWidthTable, the width-value will be used, but the height is ignored... | How do i set row height in a table? | I'm using the python library borb to create a PDF document.
I want to set the row height in a table. If i use
TableCell(paragraph, preferred_width=Decimal(150), preferred_height=Decimal(200))
in a FlexibleColumnWidthTable, the width-value will be used, but the height is ignored.
Is there another way to set the height ... | [
"disclaimer I am the author of the library you are using.\nI would recommend you issue a bug ticket on the GitHub repository. TableCell is meant to take into account the preferences.\nIt may decide not to do when layout becomes impossible.\nAs an interim measure, you can wrap your LayoutElement objects in a custom ... | [
0
] | [] | [] | [
"borb",
"pdf",
"python"
] | stackoverflow_0074421535_borb_pdf_python.txt |
Q:
How to instantiate nested class
How can I instantiate a variable of type UseInternalClass?
MyInstance = ParentClass.UseInternalClass(something=ParentClass.InternalClass({1:2}))
If I try the former code, I get an error:
NameError: name 'ParentClass' is not defined
When I want to instantiate an type of a nested cl... | How to instantiate nested class | How can I instantiate a variable of type UseInternalClass?
MyInstance = ParentClass.UseInternalClass(something=ParentClass.InternalClass({1:2}))
If I try the former code, I get an error:
NameError: name 'ParentClass' is not defined
When I want to instantiate an type of a nested class
class ParentClass(object):
cl... | [
"You cannot use \"ParentClass\" inside the definition of the parent class since the interpreter have not yet define the class object named ParentClass. Also, InternalClass will not be define until the class ParentClass is completly define.\nNote: I'm note sure what you are trying to do, but if you explain your end ... | [
1,
1,
0,
0,
0
] | [] | [] | [
"inner_classes",
"python"
] | stackoverflow_0049867582_inner_classes_python.txt |
Q:
Getting the same response different URL
I'm getting the same response from these 2 URLs:
First URL
Second URL
This is the code I'm using:
import requests
url = "https://www.amazon.it/blackfriday"
querystring = {"ref_":"nav_cs_gb_td_bf_dt_cr","deals-widget":"{\"version\":1,\"viewIndex\":60,\"presetId\":\"deals... | Getting the same response different URL | I'm getting the same response from these 2 URLs:
First URL
Second URL
This is the code I'm using:
import requests
url = "https://www.amazon.it/blackfriday"
querystring = {"ref_":"nav_cs_gb_td_bf_dt_cr","deals-widget":"{\"version\":1,\"viewIndex\":60,\"presetId\":\"deals-collection-all-deals\",\"sorting\":\"BY_SCO... | [
"You have to trick the server into thinking you are a browser. You can accomplish this by setting the user agent header.\nheaders = {'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36',\"cookie\": \"session-id=260-4643637-2647537; session... | [
0
] | [] | [] | [
"ajax",
"python",
"request",
"url",
"web_scraping"
] | stackoverflow_0074501741_ajax_python_request_url_web_scraping.txt |
Q:
List Indexing using range() and len() not working
I am trying to parse through a data structure and I have used a for loop initializing a variable i and using the range() function. I originally set my range to be the size of the records: 25,173 but then I kept receiving an
-----------------------------------------... | List Indexing using range() and len() not working | I am trying to parse through a data structure and I have used a for loop initializing a variable i and using the range() function. I originally set my range to be the size of the records: 25,173 but then I kept receiving an
---------------------------------------------------------------------------
IndexError ... | [
"elif int(Data([\"TEAM_ID_AWAY\"][i])) == const_home_team_id\n\nYour parentheses are in the wrong place.\nYou have parentheses around ([\"TEAM_ID_AWAY\"][i]), therefore it is trying to take the i'th index of the single-element list [\"TEAM_ID_AWAY\"].\nYou want Data[\"TEAM_ID_AWAY\"][i], not Data([\"TEAM_ID_AWAY\"]... | [
0,
0
] | [] | [] | [
"indexing",
"list",
"python"
] | stackoverflow_0074501871_indexing_list_python.txt |
Q:
Change values of a certain range of columns based on another range of columns of the same data frame
I have this df
x y1 y2 y3 y4 d1 d2 d3 d4
0 -17.7 7 NaN NaN NaN 5 NaN 4 NaN
1 -15.0 ... | Change values of a certain range of columns based on another range of columns of the same data frame | I have this df
x y1 y2 y3 y4 d1 d2 d3 d4
0 -17.7 7 NaN NaN NaN 5 NaN 4 NaN
1 -15.0 NaN NaN NaN 3 4 NaN NaN 8
2 -12.5 NaN Na... | [
"You can use where with a boolean matrix:\ndf[['d1', 'd2', 'd3', 'd4']] = df.filter(like='d').where(df.filter(like='y').notna().to_numpy())\n\nOutput:\n x y1 y2 y3 y4 d1 d2 d3 d4\n0 -17.7 7.0 NaN NaN NaN 5.0 NaN NaN NaN\n1 -15.0 NaN NaN NaN 3.0 NaN NaN NaN 8.0\n2 -12.5 NaN NaN 2.0 ... | [
3
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074501938_dataframe_pandas_python.txt |
Q:
How to make the x-axis of a histogram (df.hist) finer (more values within a given space)
I have the following code. I am looping through variables (dataframe columns) and create histograms. I have attached below an example of a graph for the column newerdf['distance'].
I would like to increase the number of values... | How to make the x-axis of a histogram (df.hist) finer (more values within a given space) | I have the following code. I am looping through variables (dataframe columns) and create histograms. I have attached below an example of a graph for the column newerdf['distance'].
I would like to increase the number of values on the x-axis, so that the x-axis values on the graph below say 0,1,2,3,4,5,6,7,8,9,10 rather... | [
"With the following toy dataframe and plot in a Jupyter notebook:\nimport pandas as pd\nfrom matplotlib import pyplot as plt\n\ndf = pd.DataFrame(\n {\n \"A\": [\n 1.5660150383101321,\n 0.3145564820111119,\n 0.36639603868848436,\n 1.0212995716690398,\n ... | [
1
] | [] | [] | [
"jupyter_notebook",
"matplotlib",
"pandas",
"python"
] | stackoverflow_0074483004_jupyter_notebook_matplotlib_pandas_python.txt |
Q:
Python 3.9.12: f-string error - SyntaxError: invalid syntax
I am using Spyder with Python 3.9.12
Here is the code I have inside Spyder:
user_input = (input('Please enter a number between 1 and 12:>>' ))
while (not user_input.isdigit()) or (int(user_input) < 1 or int(user_input) > 12):
print('Must be an intege... | Python 3.9.12: f-string error - SyntaxError: invalid syntax | I am using Spyder with Python 3.9.12
Here is the code I have inside Spyder:
user_input = (input('Please enter a number between 1 and 12:>>' ))
while (not user_input.isdigit()) or (int(user_input) < 1 or int(user_input) > 12):
print('Must be an integer between 1 and 12')
user_input = input('Please make a select... | [
"You used double quotes in f\"\"{i}\" x \"{user_input}\" = \"{i=user_input}\"\". Now the string starts at the first double quote and ends at the second. The following text now leads to a SyntaxError.\nYou could use triple quotes to define the string. The fourth is now part of the strings content.\nf\"\"\"\"{i}\" x ... | [
0
] | [] | [] | [
"anaconda",
"f_string",
"python",
"python_3.x",
"spyder"
] | stackoverflow_0074502004_anaconda_f_string_python_python_3.x_spyder.txt |
Q:
How can I download attachments from emails sent as attachments with Python?
I received an email with multiple emails attached. Each email has .xls file that I want to download.
How can I do this in Python?
(I use the Outlook app)
enter image description here
I tried to move these emails to my inbox and run the cod... | How can I download attachments from emails sent as attachments with Python? | I received an email with multiple emails attached. Each email has .xls file that I want to download.
How can I do this in Python?
(I use the Outlook app)
enter image description here
I tried to move these emails to my inbox and run the code I already use:
path = 'C:/Users/moliveira/Desktop/projeto_email'
os.chdir(p... | [
"You can save the attached item to the disk and then execute it programmatically to be opened in Outlook (it is a singleton which means only one instance of Outlook can be run at the same time).\nAlso if the attached mail item is saved to the disk you may use the NameSpace.OpenSharedItem method which opens a shared... | [
0
] | [] | [] | [
"email_attachments",
"office_automation",
"outlook",
"python",
"win32com"
] | stackoverflow_0074494148_email_attachments_office_automation_outlook_python_win32com.txt |
Q:
How to find and replace words in a python file?
There is a template file:
ZOYX:_sName_:IUA:S:BCSU,_sNumb_:AFAST;
ZOYP:IUA:_sName_:"_ip1_",,49155:"_ip2_",30,,,49155;
ZDWP:_sName_:BCSU,_sNumb_:0,3:_sName_;
ZOYS:IUA:_sName_:ACT;
ZERC:BTS=58,TRX=_tNumb_::FREQ=567,TSC=0,:DNAME=_sName_:CH0=TCHD,CH1=TCHD,CH2=TCHD,CH3... | How to find and replace words in a python file? | There is a template file:
ZOYX:_sName_:IUA:S:BCSU,_sNumb_:AFAST;
ZOYP:IUA:_sName_:"_ip1_",,49155:"_ip2_",30,,,49155;
ZDWP:_sName_:BCSU,_sNumb_:0,3:_sName_;
ZOYS:IUA:_sName_:ACT;
ZERC:BTS=58,TRX=_tNumb_::FREQ=567,TSC=0,:DNAME=_sName_:CH0=TCHD,CH1=TCHD,CH2=TCHD,CH3=TCHD,CH4=TCHD,CH5=TCHD,CH6=TCHD,CH7=TCHD:;
ZERM:BTS... | [
"In your Python code you have just read text from template.txt file and append it to output.txt file.\nJust add below code replace key in keys list with user inputs.\nfor key, value in dictionary.items():\n rFile = rFile.replace(key, str(value))\n \n\nAlso, in line keys=['_ip1_', '_ip2_', '_sName_', '_sNumb_'... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074500925_python.txt |
Q:
Get an error when creating voice channel not sure what to do
I'm creating a command that will create voice channels, It takes a few arguments from the user and makes a voice channel with it. Here is the code -
##TEST CREATE VC
@bot.command(name="createvoice")
async def createvoice(ctx, name = "Voice Channel", user... | Get an error when creating voice channel not sure what to do | I'm creating a command that will create voice channels, It takes a few arguments from the user and makes a voice channel with it. Here is the code -
##TEST CREATE VC
@bot.command(name="createvoice")
async def createvoice(ctx, name = "Voice Channel", user_limit = 5,):
guild = ctx.message.author.guild
await guild... | [
"You have to provide a name. When I provided a name it worked for me. To do this change\nawait guild.create_voice_channel(name, user_limit=5)\n\nto\nawait guild.create_voice_channel(name=\"VOICE_CHANNEL_NAME\", user_limit=5)\n\nand replace VOICE_CHANNEL_NAME to your wanted voice channel name.\nIf you want to have t... | [
0
] | [] | [] | [
"bots",
"discord.py",
"nextcord",
"python"
] | stackoverflow_0074501957_bots_discord.py_nextcord_python.txt |
Q:
How do I measure elapsed time in Python?
I want to measure the time it took to execute a function. I couldn't get timeit to work:
import timeit
start = timeit.timeit()
print("hello")
end = timeit.timeit()
print(end - start)
A:
Use time.time() to measure the elapsed wall-clock time between two points:
import time... | How do I measure elapsed time in Python? | I want to measure the time it took to execute a function. I couldn't get timeit to work:
import timeit
start = timeit.timeit()
print("hello")
end = timeit.timeit()
print(end - start)
| [
"Use time.time() to measure the elapsed wall-clock time between two points:\nimport time\n\nstart = time.time()\nprint(\"hello\")\nend = time.time()\nprint(end - start)\n\nThis gives the execution time in seconds.\n\nAnother option since Python 3.3 might be to use perf_counter or process_time, depending on your req... | [
2301,
1058,
223,
209,
105,
90,
70,
65,
60,
49,
31,
21,
21,
21,
21,
19,
18,
14,
13,
13,
12,
10,
10,
9,
8,
8,
7,
7,
6,
5,
5,
3,
3,
2,
1,
0,
0,
0,
0,
0
] | [
"In addition to %timeit in ipython you can also use %%timeit for multi-line code snippets:\nIn [1]: %%timeit\n ...: complex_func()\n ...: 2 + 2 == 5\n ...:\n ...:\n\n1 s ± 1.93 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n\nAlso it can be used in jupyter notebook the same way, just put magic %%tim... | [
-3
] | [
"measure",
"performance",
"python",
"timeit"
] | stackoverflow_0007370801_measure_performance_python_timeit.txt |
Q:
Using python library Rasterio to create a subset of a TIFF image and then display it and save it?
I have two Raster images, one from band 4 with a B4 at the end and another from band 5 with B5 at the end. I want to subset the B5 raster to 800x600, then display it and save it as a GeoTiff. Then I want to compute th... | Using python library Rasterio to create a subset of a TIFF image and then display it and save it? | I have two Raster images, one from band 4 with a B4 at the end and another from band 5 with B5 at the end. I want to subset the B5 raster to 800x600, then display it and save it as a GeoTiff. Then I want to compute the NDVI (I assume I'll need both the B4 and B5 to do this, but not sure). Then I want to display the NDV... | [
"You only read the first band when you used the read method. Also things might be purple because of no data. To check:\nimport numpy as np\nnp.any(raster == -9999)\n\nif True then you have no data\nTo fix:\nNODATA = -9999\nif np.any(raster == NODATA):\n mosaic[raster == NODATA] = np.nan \n\n"
] | [
0
] | [] | [] | [
"python",
"rasterio"
] | stackoverflow_0053362947_python_rasterio.txt |
Q:
Possible data Ingest count issue in FeatureStore
I see mistake, that count of values in FeatureStore Statistic do not fit with amount of ingested values, see sample
...
project_name = 'test-load'
project = mlrun.get_or_create_project(project_name, context='./', user_project=True)
..
fset = fstore.FeatureSet("test0... | Possible data Ingest count issue in FeatureStore | I see mistake, that count of values in FeatureStore Statistic do not fit with amount of ingested values, see sample
...
project_name = 'test-load'
project = mlrun.get_or_create_project(project_name, context='./', user_project=True)
..
fset = fstore.FeatureSet("test01", entities=['id'])
# ingest 3 values
fstore.ingest(f... | [
"The key is that statistics reflect the data for the last ingestion ONLY. It means, that number of values based on ingestions is without mistakes, you can check total of values based on e.g. FeatureVector, see sample code\n...\nfeatures = [\"test01.F_2\"]\n\nvector = fstore.FeatureVector(\"test_vector\",features=fe... | [
4
] | [] | [] | [
"feature_store",
"mlrun",
"python"
] | stackoverflow_0074502045_feature_store_mlrun_python.txt |
Q:
Python vs Javascript execution time
I tried solving Maximum Subarray using both Javascript(Node.js) and Python, with brute force algorithm. Here's my code:
Using python:
from datetime import datetime
from random import randint
arr = [randint(-1000,1000) for i in range(1000)]
def bruteForce(a):
l = len(a)
max... | Python vs Javascript execution time | I tried solving Maximum Subarray using both Javascript(Node.js) and Python, with brute force algorithm. Here's my code:
Using python:
from datetime import datetime
from random import randint
arr = [randint(-1000,1000) for i in range(1000)]
def bruteForce(a):
l = len(a)
max = 0
for i in range(l):
sum = 0
... | [
"Yes it is. All modern JS engines are quite fast, and significantly faster than Python. But that doesn’t always matter, the context is important when deciding between languages based on performance.\n",
"Python is not per se slower than Javascript, it depends on the implementation.\nHere the results comparing nod... | [
1,
1
] | [] | [] | [
"javascript",
"python"
] | stackoverflow_0071679094_javascript_python.txt |
Q:
Azure function deployment of single Python script and process of installation of requirements.txt in Azure Functions
I am completely new to Azure. I recently deployed my Python Script on Azure Functions (HTTP). It worked completely fine for me. The problem I faced is when my Python script needed some packages to b... | Azure function deployment of single Python script and process of installation of requirements.txt in Azure Functions | I am completely new to Azure. I recently deployed my Python Script on Azure Functions (HTTP). It worked completely fine for me. The problem I faced is when my Python script needed some packages to be installed like (pandas, psycopy2). Although I put them in requirements.txt file. And after deployment requirements.txt i... | [
"I've installed a package ('requests') and ran http trigger function locally by creating a new function app with python3.9. I was able to deploy it to Azure and triggered successfully without any error.\nNote: Make sure that while adding any package in requirements.txt file, install package in the project directory... | [
0
] | [] | [] | [
"azure",
"azure_functions",
"azure_pipelines_yaml",
"python",
"requirements.txt"
] | stackoverflow_0074492187_azure_azure_functions_azure_pipelines_yaml_python_requirements.txt.txt |
Q:
Python get JSON Response from XHR Request
I've been trying for some time to build a get request using requests and other python tools, which should actually return a JSON.
To get closer to the topic, I first try to reproduce the whole thing in the browser. Thereby I already come to limits.
It's about this URL:
htt... | Python get JSON Response from XHR Request | I've been trying for some time to build a get request using requests and other python tools, which should actually return a JSON.
To get closer to the topic, I first try to reproduce the whole thing in the browser. Thereby I already come to limits.
It's about this URL:
https://unverpackt-verband.de/map
When I look at t... | [
"I'm not sure if you're looking for the following?\nimport requests\nimport pandas as pd\n\n\nheaders = {'accept': 'application/json, text/plain, */*',\n 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.79 Safari/537.36'\n}\n\nurl = 'https://api.unverpackt-v... | [
1
] | [] | [] | [
"python",
"python_3.x",
"python_requests",
"web_scraping"
] | stackoverflow_0074501818_python_python_3.x_python_requests_web_scraping.txt |
Q:
How is PyTorch's Class BCEWithLogitsLoss exactly implemented?
According to the PyTorch documentation, the advantage of the class BCEWithLogitsLoss() is that one can use the
log-sum-exp trick for numerical stability.
If we use the class BCEWithLogitsLoss() with the parameter reduction set to None, they have a for... | How is PyTorch's Class BCEWithLogitsLoss exactly implemented? | According to the PyTorch documentation, the advantage of the class BCEWithLogitsLoss() is that one can use the
log-sum-exp trick for numerical stability.
If we use the class BCEWithLogitsLoss() with the parameter reduction set to None, they have a formula for that:
I now simplified the terms, and obtain after some l... | [
"nn.BCEWithLogitsLoss is actually just cross entropy loss that comes inside a sigmoid function. It may be used in case your model's output layer is not wrapped with sigmoid. Typically used with the raw output of a single output layer neuron.\nSimply put, your model's output say pred will be a raw value. In order to... | [
8,
4,
0
] | [] | [] | [
"deep_learning",
"implementation",
"loss",
"python",
"pytorch"
] | stackoverflow_0066906884_deep_learning_implementation_loss_python_pytorch.txt |
Q:
How to display images in python simple gui from a api url
I want to read a image from api, but I am getting a error TypeError: 'module' object is not callable. I am trying to make a random meme generator
import PySimpleGUI as sg
from PIL import Image
import requests, json
cutURL = 'https://meme-api-python.herok... | How to display images in python simple gui from a api url | I want to read a image from api, but I am getting a error TypeError: 'module' object is not callable. I am trying to make a random meme generator
import PySimpleGUI as sg
from PIL import Image
import requests, json
cutURL = 'https://meme-api-python.herokuapp.com/gimme'
imageURL = json.loads(requests.get(cutURL).c... | [
"PIL.Image is a module, you can not call it by Image(...), maybe you need call it by Image.open(...). At the same, tkinter/PySimpleGUI cannot handle JPG image, so conversion to PNG image is required.\nfrom io import BytesIO\nimport PySimpleGUI as sg\nfrom PIL import Image\nimport requests, json\n\ndef image_to_data... | [
2,
1,
1
] | [] | [] | [
"api",
"pysimplegui",
"python"
] | stackoverflow_0074501874_api_pysimplegui_python.txt |
Q:
How can I convert this tensoflow code to pytorch?
How can I convert this tensoflow code to pytorch?
#tensoflow
Conv2D(
self.filter_1, (1, 64),
activation='elu',
padding="same",
kernel_constraint=max_norm(2., axis=(0, 1, 2))
)
nn.Sequential(
nn.Conv2D(16, (1, 64),
padding="same",
... | How can I convert this tensoflow code to pytorch? | How can I convert this tensoflow code to pytorch?
#tensoflow
Conv2D(
self.filter_1, (1, 64),
activation='elu',
padding="same",
kernel_constraint=max_norm(2., axis=(0, 1, 2))
)
nn.Sequential(
nn.Conv2D(16, (1, 64),
padding="same",
kernel_constraint=max_norm(2., axis=(0, 1, 2)),... | [
"You need two things:\n\nYou need to know what the input channel size is. In your example, you've only given the number of output channels, 16. Keras calculates this on its own during runtime, but you have to specify input channels when making torch nn.Conv2d.\nYou need to implement the max_norm constraint on the c... | [
2
] | [] | [] | [
"python",
"pytorch",
"tensorflow"
] | stackoverflow_0074498770_python_pytorch_tensorflow.txt |
Q:
How to set default python version for py.exe when multiple versions are installed in windows
I have both 3.10 and 3.11b3 installed on my windows 10 machine. I'd like py.exe to launch 3.10.
I had read that I should create py.ini and pyw.ini in both c:\windows and C:\Users\<user>\AppData\Local\Programs\Python\Launch... | How to set default python version for py.exe when multiple versions are installed in windows | I have both 3.10 and 3.11b3 installed on my windows 10 machine. I'd like py.exe to launch 3.10.
I had read that I should create py.ini and pyw.ini in both c:\windows and C:\Users\<user>\AppData\Local\Programs\Python\Launcher\ and the files should contain:
[defaults]
python=3.10
Multiple Python versions installed : how... | [
"Check the encoding of your .ini files: They should be in UTF-8.\n(UTF-8 with BOM doesn't work. Bug reported here).\nThen follow the steps mentioned in this answer.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0072550867_python.txt |
Q:
Python: Convert multiple categorical features to dummy variables efficiently in a loop?
I have a python dataframe and want to convert categorical features to dummy variables. I'm doing a logreg. Right now I only know how to do it manually one by one like below:
sex = pd.get_dummies(train['Sex'], drop_first=True)... | Python: Convert multiple categorical features to dummy variables efficiently in a loop? | I have a python dataframe and want to convert categorical features to dummy variables. I'm doing a logreg. Right now I only know how to do it manually one by one like below:
sex = pd.get_dummies(train['Sex'], drop_first=True)
embark = pd.get_dummies(train['Embarked'], drop_first=True)
identity = pd.get_dummies(train[... | [
"categories = ['Sex', 'Embarked', 'Identity', 'Religion', ...]\nsex, embark, identity, religion, ... = [pd.get_dummies(train[c], drop_first=True) for c in categories]\n\n"
] | [
2
] | [] | [] | [
"categorical_data",
"dummy_variable",
"for_loop",
"python"
] | stackoverflow_0074502252_categorical_data_dummy_variable_for_loop_python.txt |
Q:
How do I find the intersection point of two line SEGMENTS, if one exists?
I have two line segments described as below:
# Segment 1
((x1, y1), (x2, y2))
# Segment 2
((x1, y1), (x2, y2))
I need a way to find their intersection point if one exists, using no third-party modules. I know people have asked this questio... | How do I find the intersection point of two line SEGMENTS, if one exists? | I have two line segments described as below:
# Segment 1
((x1, y1), (x2, y2))
# Segment 2
((x1, y1), (x2, y2))
I need a way to find their intersection point if one exists, using no third-party modules. I know people have asked this question before, but every single answer I've found either doesn't always work or uses... | [
"Here's a very simple algorithm using basic algebra. There are more efficient ways to do this, as shown in the question OP shared, but for people that don't know any linear algebra they won't be particularly helpful.\nGiven two segments, you can use their endpoints to find the equation for each line using the point... | [
1
] | [] | [] | [
"intersection",
"line_segment",
"math",
"python"
] | stackoverflow_0074502061_intersection_line_segment_math_python.txt |
Q:
How to communicate from one python script with another via network?
I have a server side (Python 3) and a client side (Python 2.7), i am trying to use the socket module.
The idea is, that the server side is permanently active and the client socket connects through call of a function. Then data needs to be sent fro... | How to communicate from one python script with another via network? | I have a server side (Python 3) and a client side (Python 2.7), i am trying to use the socket module.
The idea is, that the server side is permanently active and the client socket connects through call of a function. Then data needs to be sent from server to client until the client disconnects (manually). The server sh... | [
"You simply need to add a while True loop on your server side, corrently you are only accepting one connection, and after the connection is closed the program stops. Try this on your server file:\nimport socket\n\nHOST = \"127.0.0.1\"\nPORT = 65432\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.bind((HOS... | [
0
] | [] | [] | [
"client",
"networking",
"python",
"server",
"sockets"
] | stackoverflow_0074502243_client_networking_python_server_sockets.txt |
Q:
Compare two columns from two different data frame with two conditions
The context here is that I'm comparing the values of two columns—the key and the date. If the criterion is met, we will now create a new column with the flag = Y else ""
Condition: if key are matching and date in df1 > date in df2 then "Y" else ... | Compare two columns from two different data frame with two conditions | The context here is that I'm comparing the values of two columns—the key and the date. If the criterion is met, we will now create a new column with the flag = Y else ""
Condition: if key are matching and date in df1 > date in df2 then "Y" else ""
We will therefore iterate through all of the rows in df1 and see if the ... | [
"You can use pandas.Series.gt to compare the two dates then pandas.DataFrame.loc with a boolean mask to create the new column and flag it at the same time.\ndf1.loc[df1['Date'].gt(df2['Date']), \"Flag\"]= \"Y\"\n\n# Output :\nprint(df1)\n\n Key Date Another Flag\n0 123 2022-03-04 Apple Y\n1 321 2022-... | [
1,
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074502143_pandas_python.txt |
Q:
Python float to Decimal conversion
Python Decimal doesn't support being constructed from float; it expects that you have to convert float to a string first.
This is very inconvenient since standard string formatters for float require that you specify number of decimal places rather than significant places. So if ... | Python float to Decimal conversion | Python Decimal doesn't support being constructed from float; it expects that you have to convert float to a string first.
This is very inconvenient since standard string formatters for float require that you specify number of decimal places rather than significant places. So if you have a number that could have as man... | [
"Python <2.7\n\"%.15g\" % f\n\nOr in Python 3.0:\nformat(f, \".15g\")\n\nPython 2.7+, 3.2+\nJust pass the float to Decimal constructor directly, like this:\nfrom decimal import Decimal\nDecimal(f)\n\n",
"You said in your question: \n\nCan someone suggest a good way to\n convert from float to Decimal\n preservin... | [
73,
31,
31,
6,
5,
4,
2,
2,
2,
1,
0,
0,
0
] | [] | [] | [
"decimal",
"python"
] | stackoverflow_0000316238_decimal_python.txt |
Q:
Keyboard module multiple if
import keyboard
while True:
if keyboard.read_key() == "up":
print("up")
if keyboard.read_key() == "down":
print("down")
if keyboard.read_key() == "enter":
print("enter")
Sometimes the print function only run after second key press.
Python 3.11
I lit... | Keyboard module multiple if | import keyboard
while True:
if keyboard.read_key() == "up":
print("up")
if keyboard.read_key() == "down":
print("down")
if keyboard.read_key() == "enter":
print("enter")
Sometimes the print function only run after second key press.
Python 3.11
I literally tried every other module a... | [
"To make the code a bit cleaner, you can consider using a dictionary with messages:\nimport keyboard\nmessage = {\"up\": \"up\", \"down\": \"down\", \"enter\": \"enter\"}\nwhile True:\n key = keyboard.read_key()\n \n if key in message:\n print(message[key])\n while keyboard.is_pressed(key):... | [
0
] | [] | [] | [
"keyboard",
"python"
] | stackoverflow_0074502206_keyboard_python.txt |
Q:
How to remove backslash from JSON file
Currently using python to create the JSON, here is a snippet of my output:
"{\"ownerName\":{\"0\":\"VANGUARD GROUP INC\",\"1\":\"BLACKROCK INC.\"
...and so on
The code I've used is below:
import requests
import pandas as pd
import json
headers = {
'accept': 'application... | How to remove backslash from JSON file | Currently using python to create the JSON, here is a snippet of my output:
"{\"ownerName\":{\"0\":\"VANGUARD GROUP INC\",\"1\":\"BLACKROCK INC.\"
...and so on
The code I've used is below:
import requests
import pandas as pd
import json
headers = {
'accept': 'application/json, text/plain, */*',
'origin': 'http... | [
"You're double-encoding the Json, so that's why you have the escaped output. Try:\nimport requests\nimport pandas as pd\nimport json\n\nheaders = {\n \"accept\": \"application/json, text/plain, */*\",\n \"origin\": \"https://www.nasdaq.com\",\n \"User-Agent\": \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/... | [
2
] | [] | [] | [
"dataframe",
"json",
"pandas",
"python"
] | stackoverflow_0074501229_dataframe_json_pandas_python.txt |
Q:
Detecting a specific color in a circular area and adding horizontal lines inside the circle
I was working to reproduce an optical illusion that you find here(image) but I having trouble adding horizontal lines inside of the circles:
My attempt so far:
-Detect the certain colors of the circles
-Detect contours, and... | Detecting a specific color in a circular area and adding horizontal lines inside the circle | I was working to reproduce an optical illusion that you find here(image) but I having trouble adding horizontal lines inside of the circles:
My attempt so far:
-Detect the certain colors of the circles
-Detect contours, and extract circle center points, and radius
-Then try to draw horizontal lines (which I failed)
Her... | [
"As @fmw42 pointed out in the comment, splitting the RGB channels and applying a mask is very effective at being able to fill the inside of the circles with horizontal lines.\nimport numpy as np\nimport cv2\n\nimg = 255*np.ones((800, 800, 3), np.uint8)\nheight, width,_ = img.shape\nfor i in range(0, height, 15):\n ... | [
1
] | [] | [] | [
"colors",
"geometry",
"image_processing",
"opencv",
"python"
] | stackoverflow_0074500038_colors_geometry_image_processing_opencv_python.txt |
Q:
Is there a way to convert number words to Integers?
I need to convert one into 1, two into 2 and so on.
Is there a way to do this with a library or a class or anything?
A:
The majority of this code is to set up the numwords dict, which is only done on the first call.
def text2int(textnum, numwords={}):
if no... | Is there a way to convert number words to Integers? | I need to convert one into 1, two into 2 and so on.
Is there a way to do this with a library or a class or anything?
| [
"The majority of this code is to set up the numwords dict, which is only done on the first call.\ndef text2int(textnum, numwords={}):\n if not numwords:\n units = [\n \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\",\n \"nine\", \"ten\", \"eleven\", \"tw... | [
138,
37,
17,
16,
12,
7,
4,
4,
3,
1,
1,
0,
0,
0,
0
] | [
"This code works for a series data:\nimport pandas as pd\nmylist = pd.Series(['one','two','three'])\nmylist1 = []\nfor x in range(len(mylist)):\n mylist1.append(w2n.word_to_num(mylist[x]))\nprint(mylist1)\n\n",
"This code works only for numbers below 99. Both word to int and int to word (for rest need to imple... | [
-1,
-3
] | [
"integer",
"numbers",
"python",
"string",
"text"
] | stackoverflow_0000493174_integer_numbers_python_string_text.txt |
Q:
How to update lables in a python frame class with (after) code
I'm attempting a Python frame class with a lable that updates every time period. I can't seem to get he configure thing to work for me. Thanks
from tkinter import * # get base widget set
from tkinter.messagebox import askokcance... | How to update lables in a python frame class with (after) code | I'm attempting a Python frame class with a lable that updates every time period. I can't seem to get he configure thing to work for me. Thanks
from tkinter import * # get base widget set
from tkinter.messagebox import askokcancel
from datetime import datetime
class SensorUpdate(Frame) :
def ... | [
"After spending some quality time with 3000 pages of Lutz texts, I've found a solution using two classes one for the basics of display and one for the update using the (after) command. Any help on my first method is apprecieated. I can make this work at least even if I'm not sure why the first one doesn't\nfrom tk... | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074490926_python_tkinter.txt |
Q:
I need help to automatically DEcensore a text (lot's of text to be prosseced)
I have a web story that has cencored word in it with asterix
right now i'm doing it with a simple and dumb str.replace
but as you can imagine this is a pain and I need to search in the text to find all instance of the censoring
here is b... | I need help to automatically DEcensore a text (lot's of text to be prosseced) | I have a web story that has cencored word in it with asterix
right now i'm doing it with a simple and dumb str.replace
but as you can imagine this is a pain and I need to search in the text to find all instance of the censoring
here is bastard instance that are capitalized, plurial and with asterix in different places
... | [
"Using regex alone will likely not result in a full solution for this. You would likely have an easier time if you have a simple list of the words that you want to restore, and use Levenshtein distance to determine which one is closest to a given word that you have found a * in.\nOne library that may help with thi... | [
1,
1
] | [] | [] | [
"dictionary",
"python",
"replace",
"string"
] | stackoverflow_0074502158_dictionary_python_replace_string.txt |
Q:
How to create a list with column name for each row of a df
i have this df:
have
and i want to make a list with the column name and data for each row who looks like this:
[{'userid': '1', 'account_holder': 'Vince', 'broker': '1090', 'account_id': '807521'},
{'userid': '2', 'account_holder': 'Joana', 'broker': '3055... | How to create a list with column name for each row of a df | i have this df:
have
and i want to make a list with the column name and data for each row who looks like this:
[{'userid': '1', 'account_holder': 'Vince', 'broker': '1090', 'account_id': '807521'},
{'userid': '2', 'account_holder': 'Joana', 'broker': '3055', 'account_id': '272167'},
{'userid': '3', 'account_holder': 'D... | [
"We can use your expected output to create a dataframe\n>>> import pandas as pd\n>>> df = pd.DataFrame([{'userid': '1', 'account_holder': 'Vince', 'broker': '1090', 'account_id': '807521'}, {'userid': '2', 'account_holder': 'Joana', 'broker': '3055', 'account_id': '272167'}, {'userid': '3', 'account_holder': 'Domin... | [
0
] | [] | [] | [
"for_loop",
"list",
"pandas",
"python"
] | stackoverflow_0074501175_for_loop_list_pandas_python.txt |
Q:
How to use commands from a txt file and store Python outputs in a txt file
Input file looks like this
I am trying do to following thing,
1-) Take shell commands from a txt file
2-) Store outputs of those commands in an another txt file.
But I am not sure how to use those commands and store them.
import os
... | How to use commands from a txt file and store Python outputs in a txt file | Input file looks like this
I am trying do to following thing,
1-) Take shell commands from a txt file
2-) Store outputs of those commands in an another txt file.
But I am not sure how to use those commands and store them.
import os
def read_file(file_name): #file_name must be a string
current_dir_path =... | [
"You can store the output of a command using subprocess. You can try the following:\nfrom subprocess import Popen, PIPE\n\ndef write_file(command):\n proc = Popen(command, shell=True, stdin=PIPE, stdout=PIPE,\n stderr=PIPE)\n ret = proc.stdout.readlines()\n output = [i.decode('ut... | [
0
] | [] | [] | [
"argparse",
"command_line_interface",
"operating_system",
"python",
"sys"
] | stackoverflow_0074501785_argparse_command_line_interface_operating_system_python_sys.txt |
Q:
How to install keyboard in python virtual environement | ImportError: You must be root to use this library on linux
I did the following for keyboard interaction;
pip install keyboard
But when I execute, I get the following error;
ImportError: You must be root to use this library on linux.
My OS is Linux, and I w... | How to install keyboard in python virtual environement | ImportError: You must be root to use this library on linux | I did the following for keyboard interaction;
pip install keyboard
But when I execute, I get the following error;
ImportError: You must be root to use this library on linux.
My OS is Linux, and I work in python virtual environment and use Spyder. In addition to pip, I also tried conda install, but none of them helped... | [
"You're not supposed to run pip as root - you're supposed to run your program as root!\n"
] | [
1
] | [
"did you tryed \"sudo su\"?\nor is the problem that youre trying to intsall it for python3?\n\"sudo pip3 install keyboard\"\n"
] | [
-1
] | [
"keyboard",
"python",
"python_3.x"
] | stackoverflow_0074502167_keyboard_python_python_3.x.txt |
Q:
Fetch large amount of data through an API endpoint Python3.7
I have a dataframe with ~100 000 CUI ids, which I would like to use at an API endpoint to fetch some information.
Below is my code:
#call UMLS API to get CUI terms
umls_cui = open('umls_cui_names.txt', 'w')
missed_cui = open('not_found_cui.txt', 'w')
de... | Fetch large amount of data through an API endpoint Python3.7 | I have a dataframe with ~100 000 CUI ids, which I would like to use at an API endpoint to fetch some information.
Below is my code:
#call UMLS API to get CUI terms
umls_cui = open('umls_cui_names.txt', 'w')
missed_cui = open('not_found_cui.txt', 'w')
def get_cui(CUI):
#api key
API = "aaaaaaaaaaaaaaaaaa... | [
"You are using the National Library of Medicine's API, and chose to ignore their ToS.\nApparently they return 502 status to non-compliant clients.\nhttps://documentation.uts.nlm.nih.gov/terms-of-service.html\n\nAPI Terms of Service\nIn order to avoid overloading our servers, NLM requires that users send no more tha... | [
0
] | [] | [] | [
"api",
"python"
] | stackoverflow_0074502444_api_python.txt |
Q:
Invalid stoi argument with torch
I've been tackling python and torch specifically lately as a hobby, and, while some API works, I keep getting invalid stoi argument exception with other very basic API torch provides.
Reproduced with the code below:
import torch
torch.cuda.is_available()
torch.cuda.current_device()... | Invalid stoi argument with torch | I've been tackling python and torch specifically lately as a hobby, and, while some API works, I keep getting invalid stoi argument exception with other very basic API torch provides.
Reproduced with the code below:
import torch
torch.cuda.is_available()
torch.cuda.current_device()
First call (is_available()) works as... | [
"As there is no other answers, and initial problem seem to have been solved, I thought I'd share some information.\nI've noticed the problem was fixed when... I updated my Nvidia driver. No idea what was the problem, and if there's anything else I unknowingly did, but updating to 526.98 did the trick for me.\nIf th... | [
0
] | [] | [] | [
"python",
"pytorch"
] | stackoverflow_0074308875_python_pytorch.txt |
Q:
Run python SCRIPT on multiple browsers at the same time using selenium
I would like to run my script on Multiple browser using selenium.
As of now I am able to perform the operation by opening one browser at a time.
Eg:- Register to amazon.
I want to be able to Register two users to amazon at the same time.
Thi... | Run python SCRIPT on multiple browsers at the same time using selenium | I would like to run my script on Multiple browser using selenium.
As of now I am able to perform the operation by opening one browser at a time.
Eg:- Register to amazon.
I want to be able to Register two users to amazon at the same time.
This is the code I have as of now.
import time
from selenium import webdriver
f... | [
"You could create multiple instances of the webdriver. You can then manipulate each individually. For example,\nfrom selenium import webdriver\ndriver1 = webdriver.Chrome()\ndriver2 = webdriver.Chrome()\ndriver1.get(\"http://google.com\")\ndriver2.get(\"http://yahoo.com\")\n\n",
"This question is a bit old at thi... | [
2,
0
] | [] | [] | [
"python",
"python_2.7",
"selenium",
"selenium_chromedriver"
] | stackoverflow_0043626313_python_python_2.7_selenium_selenium_chromedriver.txt |
Q:
Changing AWS Lambda environment variables when running test
I've got a few small Python functions that post to twitter running on AWS. I'm a novice when it comes to Lambda, knowing only enough to get the functions running.
The functions have environment variables set in Lambda with various bits of configuration, s... | Changing AWS Lambda environment variables when running test | I've got a few small Python functions that post to twitter running on AWS. I'm a novice when it comes to Lambda, knowing only enough to get the functions running.
The functions have environment variables set in Lambda with various bits of configuration, such as post frequency and the secret data for the twitter applica... | [
"That is very much possible and there are multiple ways to do it. One is to use AWS CLI's aws lambda update-function-configuration: https://docs.aws.amazon.com/cli/latest/reference/lambda/update-function-configuration.html\nAlternatively, depending on programming language that you prefer, you can use AWS SDK that a... | [
0
] | [] | [] | [
"amazon_web_services",
"aws_lambda",
"python"
] | stackoverflow_0074502175_amazon_web_services_aws_lambda_python.txt |
Q:
How to convert 2D list of string into 2D list of integers in Python
I have written the following code to read a csv file into a multidimensional list which is working fine. The problem arise when I created a function to calculate the total of 2D list. This is happening because the numbers are in string inside the ... | How to convert 2D list of string into 2D list of integers in Python | I have written the following code to read a csv file into a multidimensional list which is working fine. The problem arise when I created a function to calculate the total of 2D list. This is happening because the numbers are in string inside the 2D list i.e.
[['0', '0', '30', '2', '21', '13', '23'], .....,['8', '25', ... | [
"The TypeError tells that you try to add an str and not an int to an int. You can convert your str to an int by just wrapping int(<YourString>) arrount it.\nSo in your code it would like this:\ntotal = 0\nfor row in matrix:\n for value in row:\n total += int(value) # this line\nreturn total\n\nAlso when you rea... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074502551_python.txt |
Q:
How to make an executable file?
Code for the background image of the GUI :
bg = PhotoImage(file='images/all_button.png')
lbl_bg = Label(root, image=bg)
lbl_bg.place(x=0, y=0, relwidth=1, relheight=1)
Error
Traceback (most recent call last):
File "finalbilling.py", line 14, in <module>
File "tkinter\__init__.p... | How to make an executable file? | Code for the background image of the GUI :
bg = PhotoImage(file='images/all_button.png')
lbl_bg = Label(root, image=bg)
lbl_bg.place(x=0, y=0, relwidth=1, relheight=1)
Error
Traceback (most recent call last):
File "finalbilling.py", line 14, in <module>
File "tkinter\__init__.py", line 4061, in __init__
File "tk... | [
"You can convert the python script to a standalone executable with all its dependencies included using different python packages. One such package is pyinstaller which can be used to create executable for Windows, Mac OS X, or GNU/Linux. pyinstaller\n",
"There are many ways in which you can convert it into an exe... | [
0,
0,
0
] | [] | [] | [
"executable",
"python",
"windows"
] | stackoverflow_0066632129_executable_python_windows.txt |
Q:
Python requires ipykernel to be installed
I encounter an issue when I use the Jupyter Notebook in VS code. The screen shows "Python 3.7.8 requires ipykernel to be installed". I followed the pop-up to install ipykernel. It still does not work. The screenshot is attached. It bothers me a lot. Could anyone help me wi... | Python requires ipykernel to be installed | I encounter an issue when I use the Jupyter Notebook in VS code. The screen shows "Python 3.7.8 requires ipykernel to be installed". I followed the pop-up to install ipykernel. It still does not work. The screenshot is attached. It bothers me a lot. Could anyone help me with it? Tons of thanks.
| [
"The reason is that your current VSCode terminal is in the environment \"Deeplearning_Env\", so \"ipykernel\" is installed in the environment \"Deeplearning_Env\" instead of the environment \"base conda\" displayed in the pop-up box.\nSolution: Please use the shortcut key Ctrl+Shift+` to open a new VScode terminal,... | [
18,
12,
11,
4,
4,
2,
1,
1,
1,
1,
0,
0,
0
] | [] | [] | [
"jupyter",
"python",
"visual_studio_code"
] | stackoverflow_0064997553_jupyter_python_visual_studio_code.txt |
Q:
python why does function never reach return statement?
I always get the output None instead of False
My code:
def bi_search(elements: list, x) -> bool:
i = len(elements)/2-1
i = int(i)
print(i)
if i == 0:
return False
elif x == elements[i]:
return True
elif x < elements[i]:
... | python why does function never reach return statement? | I always get the output None instead of False
My code:
def bi_search(elements: list, x) -> bool:
i = len(elements)/2-1
i = int(i)
print(i)
if i == 0:
return False
elif x == elements[i]:
return True
elif x < elements[i]:
e = elements[0:i + 1]
bi_search(e, x)
el... | [
"You don't have return statements in the last 2 elif, you want to return the value of recursive call\ndef bi_search(elements: list, x) -> bool:\n i = len(elements)/2-1\n i = int(i)\n print(i)\n if i == 0:\n return False\n elif x == elements[i]:\n return True\n elif x < elements[i]:\n ... | [
2,
2
] | [] | [] | [
"function",
"python"
] | stackoverflow_0074502599_function_python.txt |
Q:
How to explode multiple columns of a dataframe in pyspark
I have a dataframe which consists lists in columns similar to the following. The length of the lists in all columns is not same.
Name Age Subjects Grades
[Bob] [16] [Maths,Physics,Chemistry] [A,B,C]
I want to explode the dataframe in suc... | How to explode multiple columns of a dataframe in pyspark | I have a dataframe which consists lists in columns similar to the following. The length of the lists in all columns is not same.
Name Age Subjects Grades
[Bob] [16] [Maths,Physics,Chemistry] [A,B,C]
I want to explode the dataframe in such a way that i get the following output-
Name Age Subjects Grad... | [
"PySpark has added an arrays_zip function in 2.4, which eliminates the need for a Python UDF to zip the arrays.\nimport pyspark.sql.functions as F\nfrom pyspark.sql.types import *\n\ndf = sql.createDataFrame(\n [(['Bob'], [16], ['Maths','Physics','Chemistry'], ['A','B','C'])],\n ['Name','Age','Subjects', 'Gra... | [
53,
17,
5,
1,
0,
0
] | [] | [] | [
"apache_spark",
"apache_spark_sql",
"dataframe",
"pyspark",
"python"
] | stackoverflow_0051082758_apache_spark_apache_spark_sql_dataframe_pyspark_python.txt |
Q:
Get the width of the rectangle in the plot created using matplootlib
How do I get the size (width and height) of the rectangle of a plot create with matplotlib's pyplot library. Specifically I need the width of the box:
Here is a part of the code:
import matplotlib.pyplot as plt ... | Get the width of the rectangle in the plot created using matplootlib | How do I get the size (width and height) of the rectangle of a plot create with matplotlib's pyplot library. Specifically I need the width of the box:
Here is a part of the code:
import matplotlib.pyplot as plt
plt.figure() ... | [
"You can get the with of the box using\nax.get_window_extent().transformed(ax.get_figure().dpi_scale_trans.inverted()).width*ax.get_figure().dpi\n\n"
] | [
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0062091026_matplotlib_python.txt |
Q:
ERROR: Could not build wheels for phik, which is required to install pyproject.toml-based projects
While running this command on command prompt:
PS D:\Mitali> pip install pandas-profiling
I am getting this error:
ERROR: Could not build wheels for phik, which is required to install pyproject.toml-based projects
T... | ERROR: Could not build wheels for phik, which is required to install pyproject.toml-based projects | While running this command on command prompt:
PS D:\Mitali> pip install pandas-profiling
I am getting this error:
ERROR: Could not build wheels for phik, which is required to install pyproject.toml-based projects
The entire error looks as:
Building wheels for collected packages: phik
Building wheel for phik (pyprojec... | [
"try to do this:\npip install phik==0.11.1 \npip install pandas-profiling\n\n"
] | [
0
] | [] | [] | [
"pandas",
"pandas_profiling",
"python"
] | stackoverflow_0070917594_pandas_pandas_profiling_python.txt |
Q:
How to read a webpage table using requests-html?
I am new to python and am trying to parse a table from the given website into a PANDAS DATAFRAME.
I am using modules requests-html, requests, and beautifulSoup.
Here is the website, I would like to gather the table from:
https://www.aamc.org/data-reports/workforce/i... | How to read a webpage table using requests-html? | I am new to python and am trying to parse a table from the given website into a PANDAS DATAFRAME.
I am using modules requests-html, requests, and beautifulSoup.
Here is the website, I would like to gather the table from:
https://www.aamc.org/data-reports/workforce/interactive-data/active-physicians-largest-specialties-... | [
"The data you see on the page is embedded inside <script> in form of JavaScript. You can use selenium or parse the data manually from the page. I'm using js2py module to decode the data:\nimport re\nimport js2py\nimport requests\nimport pandas as pd\n\n\nurl = \"https://www.aamc.org/data-reports/workforce/interacti... | [
2
] | [] | [] | [
"beautifulsoup",
"pandas",
"python",
"python_requests_html",
"request"
] | stackoverflow_0074502644_beautifulsoup_pandas_python_python_requests_html_request.txt |
Q:
Replace all instances of a value to another specific value
I have this part of the df
x y d n
0 -17.7 -0.785430 0.053884 y1
1 -15.0 -3820.085000 0.085000 y4
2 -12.5 2.138833 0.143237 y3
3 -12.4 1.721205 0.251180 y3
I want to replace all instances of y3 for "... | Replace all instances of a value to another specific value | I have this part of the df
x y d n
0 -17.7 -0.785430 0.053884 y1
1 -15.0 -3820.085000 0.085000 y4
2 -12.5 2.138833 0.143237 y3
3 -12.4 1.721205 0.251180 y3
I want to replace all instances of y3 for "3rd" and y4 for "4th" in column n
Output:
x y... | [
"Simple. You can use Python str functions after .str on a column.\ndf['n'] = df['n'].str.replace('y3', '3rd').replace('y4', '4th')\n\nOR\nYou can select the specific columns and replace like this\ndf[df['n'] == 'y3'] = '3rd'\ndf[df['n'] == 'y4'] = '4th'\n\nChoice is yours.\n",
"You can use regex and define a dict... | [
1,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074502635_dataframe_pandas_python.txt |
Q:
Setting limits of the colorbar in Python
I made a contour plot and a colorbar to show the range of the values I plot. The limits of the colorbar are (-0.4, 0.4) and I would like to convert them to (0, 100) with a step 20, so 0, 20, 40, 60, 80 and 100.
I tried to do that with:
plt.clim(0, 100)
plt.colorbar(label="... | Setting limits of the colorbar in Python |
I made a contour plot and a colorbar to show the range of the values I plot. The limits of the colorbar are (-0.4, 0.4) and I would like to convert them to (0, 100) with a step 20, so 0, 20, 40, 60, 80 and 100.
I tried to do that with:
plt.clim(0, 100)
plt.colorbar(label="unit name", orientation="vertical")
but inst... | [
"If you translate your array of [-0.4, 0.4] values to the range [0, 100], you will be able to plot what you need.\nThis is what I did in the example below :\nfrom random import randint\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable\n\nsize ... | [
1
] | [] | [] | [
"colorbar",
"limit",
"matplotlib",
"python"
] | stackoverflow_0074500693_colorbar_limit_matplotlib_python.txt |
Q:
Formatted print to the console in python
I have a method that returns a list of lists.
def get_ranking_matrix(self) -> list:
return self.ranking_matrix
When I call print(a.get_ranking_matrix()), I get the classic output of a two-dimensional array:
[[2, 1, 4, 3, 6, 5], [3, 1, 4, 6, 5, 2], [4, 1, 2, 6, 3, 5], [2... | Formatted print to the console in python | I have a method that returns a list of lists.
def get_ranking_matrix(self) -> list:
return self.ranking_matrix
When I call print(a.get_ranking_matrix()), I get the classic output of a two-dimensional array:
[[2, 1, 4, 3, 6, 5], [3, 1, 4, 6, 5, 2], [4, 1, 2, 6, 3, 5], [2, 1, 3, 4, 5, 6], [2, 1, 4, 5, 6, 3], [2, 1, 4... | [
"You can achieve the same output format manually like so:\ndef get_ranking_mat(the_list):\n my_str = ''\n for i in the_list:\n for elem in I:\n my_str+=str(elem)+ ' '\n my_str+='\\n'\n return my_str \n\nprint(get_ranking_mat(my_list))\n\nyou need to implement it within your class.\... | [
0
] | [] | [] | [
"console_application",
"methods",
"object",
"python",
"python_3.x"
] | stackoverflow_0074502455_console_application_methods_object_python_python_3.x.txt |
Q:
I'm pulling data from amazon with python bs4 but it's not pulling data from some links
image here
image here
I scan the links and draw the price and title of the products, but sometimes on some pages it does not attract any product, I guess it does not list the link, how do I fix it?
I gave you 2 pictures, sometim... | I'm pulling data from amazon with python bs4 but it's not pulling data from some links | image here
image here
I scan the links and draw the price and title of the products, but sometimes on some pages it does not attract any product, I guess it does not list the link, how do I fix it?
I gave you 2 pictures, sometimes they do, sometimes they don't. What is the reason for this?
`
import requests
from bs4 im... | [
"result = soup.findAll(\"div\", {\"class\":\"sg-col-4-of-24 sg-col-4-of-12 s-result-item s-asin sg-col-4-of-16 sg-col s-widget-spacing-small sg-col-4-of-20\"})\n\nBecause Amazon changed the names of classes on some pages\nnot working,\nIt works as I have given below.\nresult = soup.findAll(\"div\", {\"class\":\"s-c... | [
0
] | [] | [] | [
"beautifulsoup",
"python",
"request"
] | stackoverflow_0074502638_beautifulsoup_python_request.txt |
Q:
How to set default value for column in Google bigquery table using API from pyhton script
Class that crate column and describe it doesn't have "default_value_expression" in the constructor.
path: google/cloud/bigquery/schema.py
class SchemaField:
def __init__(
name: str,
field_type: str,
mode: Any = "NULLABLE",
de... | How to set default value for column in Google bigquery table using API from pyhton script | Class that crate column and describe it doesn't have "default_value_expression" in the constructor.
path: google/cloud/bigquery/schema.py
class SchemaField:
def __init__(
name: str,
field_type: str,
mode: Any = "NULLABLE",
description: Any = None,
fields: Any = (),
policy_tags: Any = None)
That key is displayed on the... | [
"Ensure you're using the latest version of the library. It was just released in version 3.4.0 a few days ago.\n"
] | [
1
] | [] | [] | [
"google_bigquery",
"python"
] | stackoverflow_0074500662_google_bigquery_python.txt |
Q:
Efficienctly selecting rows that end with zeros in numpy
I have a tensor / array of shape N x M, where M is less than 10 but N can potentially be > 2000. All entries are larger than or equal to zero. I want to filter out rows that either
Do not contain any zeros
End with zeros only, i.e [1,2,0,0] would be valid b... | Efficienctly selecting rows that end with zeros in numpy | I have a tensor / array of shape N x M, where M is less than 10 but N can potentially be > 2000. All entries are larger than or equal to zero. I want to filter out rows that either
Do not contain any zeros
End with zeros only, i.e [1,2,0,0] would be valid but not [1,0,2,0] or [0,0,1,2]. Put differently once a zero app... | [
"Here's one way:\nx[np.all((x == 0) == (x.cumprod(axis=1) == 0), axis=1)]\n\nThis calculates the row-wise cumulative product, matches the original array's zeros up with the cumprod array, then filters any rows where there's one or more False.\nWorkings:\nIn [3]: x\nOut[3]:\narray([[35, 25, 17],\n [12, 0, 0]... | [
4
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074502782_numpy_python.txt |
Q:
Python Query - Arrays
Create two arrays using numpy. One called students with as values.
['Janet', 'Adriana', 'Manual', 'Mohamed', 'Leann']
Another is called grades as values:
[[93, 85], [78, 80], [94, 93], [75, 90], [92, 87]]
Select all rows from grades where student is either 'Adriana' or 'Mohamed'
How do i go... | Python Query - Arrays | Create two arrays using numpy. One called students with as values.
['Janet', 'Adriana', 'Manual', 'Mohamed', 'Leann']
Another is called grades as values:
[[93, 85], [78, 80], [94, 93], [75, 90], [92, 87]]
Select all rows from grades where student is either 'Adriana' or 'Mohamed'
How do i go about this problem?
| [
"You can use numpy.isin.\nimport numpy as np\nstudents = ['Janet', 'Adriana', 'Manual', 'Mohamed', 'Leann']\ngrades = [[93, 85], [78, 80], [94, 93], [75, 90], [92, 87]]\narr_s = np.asarray(students)\narr_g = np.asarray(grades)\nmask = np.isin(arr_s, ['Adriana', 'Mohamed'])\nres = arr_g[mask]\nprint(res)\n\nOutput:\... | [
0
] | [] | [] | [
"arrays",
"list",
"numpy",
"python"
] | stackoverflow_0074502830_arrays_list_numpy_python.txt |
Q:
Shell file not found inside docker compose/dockerfile containers
I have multiple Python scripts from which I want to run a docker container. From a related question How to run multiple Python scripts and an executable files using Docker? , I found that the best way to do that is to have run.sh a shell file as foll... | Shell file not found inside docker compose/dockerfile containers | I have multiple Python scripts from which I want to run a docker container. From a related question How to run multiple Python scripts and an executable files using Docker? , I found that the best way to do that is to have run.sh a shell file as follows:
#!/bin/bash
python3 producer.py &
python3 consumer.py &
python3 t... | [
"You should explicitly specify what shell interpreter be used for running your script.\nChanging the last line to CMD [\"bash\", \"-c\", \"./run.sh\"] might solve your issue.\n",
"You need to chmod run.sh to be excecuteable:\nFROM python:3.9\n\nRUN mkdir -p /usr/src/app\n\nWORKDIR /usr/src/app\n\nCOPY requirement... | [
0,
0
] | [
"If you need to run three separate long-running processes, do not try to orchestrate them from a shell script. Instead, launch three separate containers. If you're running this via Compose, this is straightforward: have three containers all running the same image, but override the command: to run different main p... | [
-1,
-2
] | [
"docker",
"docker_compose",
"dockerfile",
"python"
] | stackoverflow_0074493795_docker_docker_compose_dockerfile_python.txt |
Q:
UnicodeEncodeError: 'charmap' codec can't encode characters
I'm trying to scrape a website, but it gives me an error.
I'm using the following code:
import urllib.request
from bs4 import BeautifulSoup
get = urllib.request.urlopen("https://www.website.com/")
html = get.read()
soup = BeautifulSoup(html)
print(soup... | UnicodeEncodeError: 'charmap' codec can't encode characters | I'm trying to scrape a website, but it gives me an error.
I'm using the following code:
import urllib.request
from bs4 import BeautifulSoup
get = urllib.request.urlopen("https://www.website.com/")
html = get.read()
soup = BeautifulSoup(html)
print(soup)
And I'm getting the following error:
File "C:\Python34\lib\enc... | [
"I was getting the same UnicodeEncodeError when saving scraped web content to a file. To fix it I replaced this code:\nwith open(fname, \"w\") as f:\n f.write(html)\n\nwith this:\nwith open(fname, \"w\", encoding=\"utf-8\") as f:\n f.write(html)\n\nIf you need to support Python 2, then use this:\nimport io\nw... | [
650,
247,
76,
47,
21,
14,
5,
5,
2
] | [
"I got the same error so I use (encoding=\"utf-8\") and it solve the error.\nThis generally happens when we got some unidentified symbol or pattern in text data that our encoder does not understand.\nwith open(\"text.txt\", \"w\", encoding='utf-8') as f:\n f.write(data)\n\nThis will solve your problem.\n",
"i... | [
-1,
-2
] | [
"beautifulsoup",
"python",
"urllib"
] | stackoverflow_0027092833_beautifulsoup_python_urllib.txt |
Q:
Sum values from a treeview column
Good,
I'm trying to sum the values of a column, while inputting it. Since I put a code in the entry and check if it exists and put it in columns in treeview, and I would like to add only the "price" values, but I can't do it, I get the data from the price column, but I can't ge... | Sum values from a treeview column | Good,
I'm trying to sum the values of a column, while inputting it. Since I put a code in the entry and check if it exists and put it in columns in treeview, and I would like to add only the "price" values, but I can't do it, I get the data from the price column, but I can't get if This 5.99 I have entered another 5.... | [
"I have already managed to solve the error, the new price is already added to the old one, thanks for making me reflect on it.\nfor self.x2 in self.r_codigo:\n print (self.x2[\"nombre\"], self.x2[\"talla\"], self.x2[\"precio\"]+\"€\")\n self.tree.insert('', 'end', text=self.x2[\"nombre\"], val... | [
0
] | [] | [] | [
"mysql",
"python",
"tkinter",
"treeview"
] | stackoverflow_0074493068_mysql_python_tkinter_treeview.txt |
Q:
Python Inserting a string
I need to insert a string (character by character) into another string at every 3rd position
For example:- string_1:-wwwaabkccgkll
String_2:- toadhp
Now I need to insert string2 char by char into string1 at every third position
So the output must be wwtaaobkaccdgkhllp
Need in Python.. eve... | Python Inserting a string | I need to insert a string (character by character) into another string at every 3rd position
For example:- string_1:-wwwaabkccgkll
String_2:- toadhp
Now I need to insert string2 char by char into string1 at every third position
So the output must be wwtaaobkaccdgkhllp
Need in Python.. even Java is ok
So i tried this
Te... | [
"You can split test_str into sub-strings to length 2, and then iterate merging them with challenge:\ndef concat3(test_str, challenge):\n chunks = [test_str[i:i+2] for i in range(0,len(test_str),2)]\n result = []\n i = j = 0\n while i<len(chunks) or j<len(challenge):\n if i<len(chunks):\n ... | [
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074499534_python.txt |
Q:
Cannot add tensor to the batch: number of elements does not match. Shapes are: [tensor]: [585,1024,3], [batch]: [600,799,3]
I am trying to train a model, at first I had dataset of 5000 images and training worked fine, Now I have added couple of more images and now my dataset contains 6,423 images. I am using pyth... | Cannot add tensor to the batch: number of elements does not match. Shapes are: [tensor]: [585,1024,3], [batch]: [600,799,3] | I am trying to train a model, at first I had dataset of 5000 images and training worked fine, Now I have added couple of more images and now my dataset contains 6,423 images. I am using python 3.6.1 on Ubuntu 18.04, my tensorflow version is 1.15 & numpy version is 1.16 (had same versions before and it worked fine).
No... | [
"It seems that the new images you've added have a resolution of 585x1024, which differs from the size that's expected by the model i.e. 600x799.\nIf so, then the solution is to resize these new images accordingly.\n",
"If you need batch size > 1, you can resize the images to a uniform size with the right image_re... | [
4,
2,
0,
0,
0
] | [] | [] | [
"python",
"tensorflow"
] | stackoverflow_0059006696_python_tensorflow.txt |
Q:
How can i implement a code so the snake won't go opposite direction
Hello i have been struggling, to make is so that the snake head can't move to the left if it is moving to the right same for up and down. I understand i need to make some direction for the snake so i can compare ot to each other i just don't know ... | How can i implement a code so the snake won't go opposite direction | Hello i have been struggling, to make is so that the snake head can't move to the left if it is moving to the right same for up and down. I understand i need to make some direction for the snake so i can compare ot to each other i just don't know how to implement this.
code:
# Snake game.
import pygame
import random
... | [
"You'll want to define a direction variable at the start of game_loop:\ndirection = 'right'\n\nYou'll then need to edit the input section of the code to something like this:\nif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT and direction != 'right':\n x1_change = -snake_block\n ... | [
1
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0074502879_pygame_python.txt |
Q:
In python, how do I make a string overlap a current string in the shell?
Each second, it prints a new line.
Is there a way to have it print ontop of the previous line?
while True:
sec += 1
if sec / 60 == sec_int:
sec = 0
mins += 1
if mins / 60 == min_int:
mins = 0
... | In python, how do I make a string overlap a current string in the shell? | Each second, it prints a new line.
Is there a way to have it print ontop of the previous line?
while True:
sec += 1
if sec / 60 == sec_int:
sec = 0
mins += 1
if mins / 60 == min_int:
mins = 0
hours += 1
if hours / 24 == hour_int:
hours ... | [
"Replace your print statement with:\nprint(f\"\\r{days}d : {hours}h : {mins}m : {sec}s\", end=\"\", flush=True)\n\n\"\\r\" is a \"control character\" which moves the cursor to the beginning of the line (\"carriage Return\"). flush=True is needed to make the display update right away--normally Python can buffer unt... | [
0
] | [] | [] | [
"display",
"loops",
"python",
"replace",
"shell"
] | stackoverflow_0074502688_display_loops_python_replace_shell.txt |
Q:
Kernel size change in convolutional neural networks
I have been working on creating a convolutional neural network from scratch, and am a little confused on how to treat kernel size for hidden convolutional layers. For example, say I have an MNIST image as input (28 x 28) and put it through the following layers.
C... | Kernel size change in convolutional neural networks | I have been working on creating a convolutional neural network from scratch, and am a little confused on how to treat kernel size for hidden convolutional layers. For example, say I have an MNIST image as input (28 x 28) and put it through the following layers.
Convolutional layer with kernel_size = (5,5) with 32 outpu... | [
"you need 64 kernel, each with the size of (32,5,5) . \ndepth(#channels) of kernels, 32 in this case, or 3 for a RGB image, 1 for gray scale etc, should always match the input depth, but values are all the same.\ne.g. if you have a 3x3 kernel like this : [-1 0 1; -2 0 2; -1 0 1] and now you want to convolve it wit... | [
0,
0
] | [] | [] | [
"conv_neural_network",
"convolution",
"neural_network",
"python",
"tensorflow"
] | stackoverflow_0052997810_conv_neural_network_convolution_neural_network_python_tensorflow.txt |
Q:
Azure Python SDK to get cost of individual resources
I want to get cost of individual resources using python script is thr any way to get the price of VM,Database etc.,
A:
Use the Azure Billing library for Python.
https://learn.microsoft.com/en-us/python/api/overview/azure/cost-management-+-billing?view=azure-py... | Azure Python SDK to get cost of individual resources | I want to get cost of individual resources using python script is thr any way to get the price of VM,Database etc.,
| [
"Use the Azure Billing library for Python.\nhttps://learn.microsoft.com/en-us/python/api/overview/azure/cost-management-+-billing?view=azure-python\n"
] | [
0
] | [] | [] | [
"azure",
"azure_python_sdk",
"python"
] | stackoverflow_0074502642_azure_azure_python_sdk_python.txt |
Q:
Get mangled attribute value of a parent class outside of a class
Imagine a parent class which has a mangled attribute, and a child class:
class Foo:
def __init__(self):
self.__is_init = False
async def init(self):
# Some custom logic here, not important
self.__is_init = True
clas... | Get mangled attribute value of a parent class outside of a class | Imagine a parent class which has a mangled attribute, and a child class:
class Foo:
def __init__(self):
self.__is_init = False
async def init(self):
# Some custom logic here, not important
self.__is_init = True
class Bar(Foo):
...
# Create class instance.
bar = Bar()
# How acce... | [
"The solution I see now is iterating over parent classes, and building a mangled attribute name dynamically:\nfrom contextlib import suppress\n\nclass MangledAttributeError(Exception):\n ...\n\ndef getattr_mangled(object_: object, name: str) -> str:\n for cls_ in getattr(object_, \"__mro__\", None) or object_... | [
1,
0
] | [] | [] | [
"python",
"python_3.x",
"python_class"
] | stackoverflow_0074502700_python_python_3.x_python_class.txt |
Q:
Streamlit Doesn't start. AttributeError: Enum LabelVisibilityOptions has no value defined for name 'ValueType'
I have a basic application. I have no experience working with streamlit. When I try
streamlit run app.py
I get the following error.
Traceback (most recent call last):
File "C:\Users\joelm\AppData\Local\... | Streamlit Doesn't start. AttributeError: Enum LabelVisibilityOptions has no value defined for name 'ValueType' | I have a basic application. I have no experience working with streamlit. When I try
streamlit run app.py
I get the following error.
Traceback (most recent call last):
File "C:\Users\joelm\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 196, in _run_module_as_main
return _run_code(code, main_globals, N... | [
"I think you should revert to streamlit 1.14 for the moment, there is a problem with 1.15.0, some issues are opened : https://github.com/streamlit/streamlit/issues/5742, https://github.com/streamlit/streamlit/issues/5743\n"
] | [
0
] | [] | [] | [
"python",
"streamlit"
] | stackoverflow_0074494209_python_streamlit.txt |
Q:
(psycopg2.OperationalError) connection to server at "localhost" (::1), port 5432 failed: FATAL: database "players" does not exist
This is a program that I had written a while ago and it had been working fine, but now when I run it I'm getting this error: sqlalchemy.exc.OperationalError: (psycopg2.OperationalError)... | (psycopg2.OperationalError) connection to server at "localhost" (::1), port 5432 failed: FATAL: database "players" does not exist | This is a program that I had written a while ago and it had been working fine, but now when I run it I'm getting this error: sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) connection to server at "localhost" (::1), port 5432 failed: FATAL: database "players" does not exist
from flask import Flask, render... | [
"you have to create the database players. The database does not exist.\n"
] | [
1
] | [] | [] | [
"flask",
"python",
"sqlalchemy"
] | stackoverflow_0073848498_flask_python_sqlalchemy.txt |
Q:
Validate user input of character and iterate how many times character exists in sentence
The while loop and for loop works individually, but combining them does no generate the desired output.
I want the user to enter a sentence, and then a character. The Character must be entered as a single 1 character, if not t... | Validate user input of character and iterate how many times character exists in sentence | The while loop and for loop works individually, but combining them does no generate the desired output.
I want the user to enter a sentence, and then a character. The Character must be entered as a single 1 character, if not then the program should ask again.
sentence = input("Type sentence: ")
sentence = sentence.lowe... | [
"Something like:\nsentence = input(\"Type sentence: \")\nsentence = sentence.lower()\nsingleCharacter = input(\"Type character: \")\n\nchar = 0\n\nwhile len(singleCharacter) != 1:\n singleCharacter = input('Enter a single character: ')\n\nprint(sum([1 for c in sentence if c == singleCharacter]))\n\nShould do wha... | [
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074502810_python.txt |
Q:
Using Python how to get list of all files in a HDFS folder?
I would like to return a listing of all files in a HDFS folder using Python or preferably Pandas in a data frame. I have looked at subprocess.Popen and that may be the best way but if so is there a way to parse out all the noise and only return the file ... | Using Python how to get list of all files in a HDFS folder? | I would like to return a listing of all files in a HDFS folder using Python or preferably Pandas in a data frame. I have looked at subprocess.Popen and that may be the best way but if so is there a way to parse out all the noise and only return the file names?
the hdfs module is out as can't get the config options. T... | [
"Once you've named the path\nfrom pathlib import Path\n\nfolder = Path(\"/tmp/favorite_folder/\")\n\nthen it's just a matter of globbing some pattern, like folder.glob(\"*.csv\").\nUse wildcard to get all names at single level:\nprint(folder.glob(\"*\"))\n\n\nTo recurse through all levels,\nyou might wish to rely o... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074502325_python.txt |
Q:
Create a column by groupby Pandas DataFrame based on tail(1).index
I want create a boolean column that said if a match on first or second half for each match in the dataframe.
Code
#First Half
firsthalf_index = df.groupby(['Date','Match']).apply(lambda x: x[(x.M >= 1) & (x.M <= 45)].tail(1).index)
#Second Half
se... | Create a column by groupby Pandas DataFrame based on tail(1).index | I want create a boolean column that said if a match on first or second half for each match in the dataframe.
Code
#First Half
firsthalf_index = df.groupby(['Date','Match']).apply(lambda x: x[(x.M >= 1) & (x.M <= 45)].tail(1).index)
#Second Half
secondhalf_index = df.groupby(['Date','Match']).apply(lambda x: x[(x.M >= ... | [
"You could do\nfirsthalf_index = ((df.M >= 1) & (df.M <= 45)).iloc[::-1].groupby([df['Date'],df['Match']]).transform('idxmax')\nsecondhalf_index =((df.M >= 46) & (df.M <= 90)).iloc[::-1].groupby([df['Date'],df['Match']]).transform('idxmax')\n\nThen\ns = df.index.to_series()\ndf[(s > firsthalf_index) & (s < secondha... | [
1
] | [] | [] | [
"group_by",
"pandas",
"python"
] | stackoverflow_0074502844_group_by_pandas_python.txt |
Q:
Python: Selenium xpath to find element with case insensitive characters?
I am able to do this
search = "View List"
driver.find_elements_by_xpath("//*/text()[normalize-space(.)='%s']/parent::*" % search)
but I need it to ignore and match all elements with text like: "VieW LiSt" or "view LIST"
search = "View List"
... | Python: Selenium xpath to find element with case insensitive characters? | I am able to do this
search = "View List"
driver.find_elements_by_xpath("//*/text()[normalize-space(.)='%s']/parent::*" % search)
but I need it to ignore and match all elements with text like: "VieW LiSt" or "view LIST"
search = "View List"
driver.find_elements_by_xpath("//*/lower-case(text())[normalize-space(.)='%s']... | [
"The lower-case() function is only supported from XPath 2.0. For XPath 1.0 you will have to use translate().\nExample code is given in this stackoverflow answer.\nEdit:\nThe selenium python bindings site has a FAQ - Does Selenium 2 supports XPath 2.0 ?:\n\nRef:\n http://seleniumhq.org/docs/03_webdriver.html#how-xp... | [
3,
0
] | [] | [] | [
"python",
"selenium",
"xpath"
] | stackoverflow_0020228962_python_selenium_xpath.txt |
Q:
Multithreading for similarity test in Python
Hello I've been working on a huge csv file which needs similarity tests done. There is 1.16million rows and to test similarity between each rows it takes approximately 7 hours. I want to use multiple threads to reduce the time it takes to do so. My function which does t... | Multithreading for similarity test in Python | Hello I've been working on a huge csv file which needs similarity tests done. There is 1.16million rows and to test similarity between each rows it takes approximately 7 hours. I want to use multiple threads to reduce the time it takes to do so. My function which does the similarity test is:
def similarity():
for i... | [
"ThreadPoolExecutor will not actually help a lot because ThreadPool is more for IO tasks. Let's say you would do 500 API calls this would work but since you are doing heavy CPU tasks it does not work. You should use ProcessPoolExecutor but also point attention that making max_workers numbers greater than the numbe... | [
0
] | [] | [] | [
"csv",
"multithreading",
"python",
"similarity"
] | stackoverflow_0074503005_csv_multithreading_python_similarity.txt |
Q:
Random Errors For No Reason
For some reason I am experiencing a lot of errors regarding my indentation. I don't see anything wrong and I have re-typed the indentation multiple times. Maybe this has something to do with my other question here?
Here is the code where the error is:
@bot.command(description="See your... | Random Errors For No Reason | For some reason I am experiencing a lot of errors regarding my indentation. I don't see anything wrong and I have re-typed the indentation multiple times. Maybe this has something to do with my other question here?
Here is the code where the error is:
@bot.command(description="See your balance or somebody else's balan... | [
"All the lines after the function definition need to be indented once more, since they have to belong to the function implementation. Like so:\n@bot.command(description=\"See your balance or somebody else's balance.\", aliases=['bal'])\nasync def balance(ctx, member: discord.Member = None):\n if member:\n ... | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074502977_python_python_3.x.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.